import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { ToastController } from '@ionic/angular';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class ServiceService {
  state: boolean;
  distance: any;
  popupMsg: any;
  popupSub: any;
  deliFee: number;
  minAmount: number;
  constructor(
    public storage: Storage,
    public toastController: ToastController
  ) {
    this.popupMsg = '';
    this.popupSub = '';
    this.state = true;
    this.distance = 10;
    this.deliFee = 7.99;
    this.minAmount = 50;
    this.storage.ready().then(() => {
      this.get('user');
    });
    this.setting().then((data: any) => {
      if (data) {
        this.distance = data.distance;
        this.minAmount = data.minAmount;
        this.deliFee = data.deliFee;
      }
    }).catch(err => {
      this.distance = 10;
      this.deliFee = 7.99;
      this.minAmount = 50;
    });
  }

  public set(settingName: string, value: any) {
    return this.storage.set(`setting:${settingName}`, value);
  }

  public async get(settingName: string) {
    return await this.storage.get(`setting:${settingName}`);
  }

  public async remove(settingName: string) {
    return await this.storage.remove(`setting:${settingName}`);
  }

  public clear() {
    this.storage.clear().then(() => {
      console.log('all keys cleared');
    });
  }

  public key2Array(item: object) {
    const response = [];
    for (const key in item) {
      if (item.hasOwnProperty(key)) {
        response.push(item[key]);
      }
    }
    return response;
  }

  public splitSep(item: object) {
    const response = [];
    for (const key in item) {
      if (item.hasOwnProperty(key)) {
        response.push(key);
      }
    }
    return response;
  }

  showToast(msg, positions, className, durations = 2000) {
    try {
      const promise1 = new Promise((resolve, reject) => {
        this.toastController
          .create({
            message: msg,
            duration: durations,
            position: positions,
            cssClass: className
          })
          .then(res => {
            res.present();
            resolve(true);
          });
      });
      return promise1;
    } catch (error) {
      console.log('error: ' + error);
    }
  }

  formatNumber(num: number) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
  }

  setting() {
    const promise = new Promise(resolve => {
      const prodRef = firebase
        .firestore()
        .collection('setting')
        .doc('basic').onSnapshot(doc => {
          console.log(doc.data());
          if (doc.exists) {
            const data = doc.data();
            this.distance = data.distance;
            this.deliFee = data.deliFee;
            this.minAmount = data.minAmount;
            resolve(data);
          }
        });
    });
    return promise;
  }

  async getBase64ImageFromUrl(imageUrl) {
    const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
    const res = await fetch(proxyUrl + imageUrl);
    const blob = await res.blob();

    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.addEventListener('load', () => {
        resolve(reader.result);
      }, false);

      reader.onerror = () => {
        return reject(this);
      };
      reader.readAsDataURL(blob);
    });
  }
}
