/**
 * @author    : Adarsh Pastakia
 * @version   : 5.0.0
 * @copyright : 2018
 * @license   : MIT
 */

// tslint:disable
import { valueConverter } from "aurelia-framework";
import { CountryCode, parsePhoneNumberFromString } from "libphonenumber-js";
import { UIFormat } from "../utils/ui-format";
import moment from 'moment';

const getPhone = (value = "", country = "us") => {
  const number = parsePhoneNumberFromString(value || "", country as CountryCode);
  return number ? number : {
    country: "",
    formatNational: () => "",
    formatInternational: () => ""
  };
};

@valueConverter("json")
export class JsonValueConverter {
  public toView(value: AnyObject): string {
    return JSON.stringify(value);
  }
}

@valueConverter("phone")
export class PhoneValueConverter {
  public toView(value: string, country = ""): string {
    return getPhone(value, country).formatInternational();
  }
}

@valueConverter("phoneLocal")
export class PhoneLocalValueConverter {
  public toView(value: string, country = "us"): string {
    return getPhone(value, country).formatNational();
  }
}

@valueConverter("phoneHtml")
export class PhoneHtmlValueConverter {
  public toView(value: string, country = ""): string {
    const phoneNumber = getPhone(value, country);
    return `<span class="ui-flag ${phoneNumber.country}"></span>&nbsp;${phoneNumber.formatInternational()}`;
  }
}

@valueConverter("phoneLocalHtml")
export class PhoneLocalHtmlValueConverter {
  public toView(value: string, country = "us"): string {
    const phoneNumber = getPhone(value, country);
    return `<span class="ui-flag ${phoneNumber.country}"></span>&nbsp;${phoneNumber.formatNational()}`;
  }
}

// Dates
@valueConverter("date")
export class DateValueConverter {
  public toView(value: string, format?: string): string {
    return UIFormat.date(value, format);
  }
}

@valueConverter("time")
export class TimeValueConverter {
  public toView(value: string, format?: string): string {
    return UIFormat.time(value, format);
  }
}

@valueConverter("datetime")
export class DatetimeValueConverter {
  public toView(value: string, format?: string): string {
    return UIFormat.datetime(value, format);
  }
}

@valueConverter("fromnow")
export class FromNowValueConverter {
  public toView(value: string): string {
    return UIFormat.fromNow(value);
  }
}

@valueConverter("age")
export class AgeValueConverter {
  public toView(value: string): string {
    return UIFormat.age(value);
  }
}

@valueConverter("utc")
export class UtcValueConverter {
  public toView(value: string): string {
    return UIFormat.utcDate(value);
  }
}

@valueConverter("iso")
export class IsoValueConverter {
  public toView(value: string): string {
    return UIFormat.dateToISO(value);
  }
}

// Numbers
@valueConverter("number")
export class NumberValueConverter {
  public toView(value: string, format?: string): string {
    return UIFormat.number(value, format);
  }
}

@valueConverter("percent")
export class PercentValueConverter {
  public toView(value: string): string {
    return UIFormat.percent(value);
  }
}

@valueConverter("euro")
export class EuroValueConverter {
  public toView(value: string): string {
    return UIFormat.euro(value);
  }
}
@valueConverter("decimal")
export class DecimalValueConverter {

  private viewVal;
  public fromView(val) {

    var src = (val as string).trim();
    if (src === "") return null;
    let fVal = parseFloat(src);

    if (isNaN(fVal) || fVal.toString() != val) {
      this.viewVal = val;
    }
    else {
      this.viewVal = null;
    }
    return val;
  }
  public toView(value: string, format?: string): string {
    if (this.viewVal != null) return this.viewVal;
    return value;
  }
}

@valueConverter("bool")
export class BoolValueConverter {
  toView(value: boolean) {
    if (value != null) {
      return (value) ? `✓` : `✖`;
    }
    return null;
  }
}

@valueConverter("currency")
export class CurrencyValueConverter {
  toView(value: number) {
    if (value != null) {
      return value.toLocaleString('de-DE', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }) + ' €';
    }
    else {
      return '';
    }
  }
}

@valueConverter("iban")
export class IbanValueConverter {
  NON_ALPHANUM = /[^a-zA-Z0-9]/g;
  EVERY_FOUR_CHARS = /(.{4})(?!$)/g;
  toView(value: string, separator = ' ') {
    if (value != null) {
      value = value.replace(this.NON_ALPHANUM, '').toUpperCase();
      return value.replace(this.EVERY_FOUR_CHARS, "$1" + separator)
    }
    else {
      return '';
    }
  }
}
@valueConverter("vcs")
export class VCSValueConverter {
  NON_ALPHANUM = /[^a-zA-Z0-9]/g;
  EVERY_FOUR_CHARS = /(.{4})(?!$)/g;
  /**
   * 
   * @param value 
   * @param isVCS 
   * Allow usage of converter even with unstructured communication
   * @returns 
   */
  toView(value: string, isVCS = true) {
    if (value == null || value.length != 12 || isVCS === false) return value;
    value = value.replace(this.NON_ALPHANUM, '').toUpperCase();
    if (value != null) {
      return `+++${value.substring(0, 3)}/${value.substring(3, 7)}/${value.substring(7)}+++`;
    }
    else {
      return '';
    }
  }
}

@valueConverter("fileSize")
export class FileSizeValueConverter {
  toView(value: number) {
    if (value && typeof (value) == 'number') {
      var formatedValue: number;
      var suffix: string;
      if (value > Math.pow(1024, 3)) {
        formatedValue = value / Math.pow(1024, 3);
        suffix = ' GB';
      }
      else if (value > Math.pow(1024, 2)) {
        formatedValue = value / Math.pow(1024, 2);
        suffix = ' MB';
      }
      else if (value > 1024) {
        formatedValue = value / 1024;
        suffix = ' KB';
      }
      else {
        formatedValue = value;
        suffix = ' B';
      }
      return formatedValue.toFixed(0) + suffix;
    }
    else {
      return '';
    }
  }
}