import { Injectable } from '@angular/core';
import { TranslatorService } from '../translator/translator.service';
import { CommonService } from '../common/common.service';
import { Platform } from '@ionic/angular';
import { AppRate } from '@ionic-native/app-rate/ngx';

@Injectable({
  providedIn: 'root'
})
export class RateService {
  public static done = 'done';
  private static app = 'full-app-rate';

  constructor(
    public ts: TranslatorService,
    public cs: CommonService,
    public platform: Platform,
    public appRate: AppRate
  ) {

  }

  public rateFeature(ratedFeedBack?: any , featureKey: string = RateService.app , delay: number = 2000) {
    if (this.isRated(featureKey)) {
      if (ratedFeedBack) {
        ratedFeedBack(true);
      }
    } else {
      setTimeout( () => {
        this.startRating(featureKey, ratedFeedBack);
      }, delay);
    }
  }

  private startRating(featureKey: string, ratedFeedBack?: any) {
    if (this.cs.isCordova()) {
      this.platform.ready().then(() => {
        this.appRate.preferences = {
          displayAppName: this.ts.trPK('general', 'app-name'),
          promptAgainForEachNewVersion: true,
          inAppReview: true,
          storeAppURL: {
            ios: 'com.ejada.hmg',
            android: 'market://details?id=com.ejada.hmg',
          },
          customLocale: this.getCustomLocals(),
          callbacks: {
            handleNegativeFeedback: () => {
              this.setAsRated(featureKey);
            //this.cs.openFeedback();
            },
            onButtonClicked: (buttonIndex) => {
              // when user click rate
              if (buttonIndex == 3) {
                this.setAsRated(featureKey);
                if (ratedFeedBack) {
                  ratedFeedBack(true);
                }
              }
            }
          }
        };
        this.appRate.promptForRating(true);
      });

    } else {

    }

  }

  private getCustomLocals() {
    return {
      title: this.ts.trPK('rate', 'mind'),
      message: this.ts.trPK('rate', 'thanks'),
      cancelButtonLabel: this.ts.trPK('rate', 'cancel'),
      laterButtonLabel: this.ts.trPK('rate', 'later'),
      rateButtonLabel: this.ts.trPK('rate', 'rate'),
      yesButtonLabel: this.ts.trPK('rate', 'yes'),
      noButtonLabel: this.ts.trPK('rate', 'not'),
      appRatePromptTitle: this.ts.trPK('rate', 'like'),
      feedbackPromptTitle: this.ts.trPK('rate', 'feedback'),
    };
  }
  private setAsRated(featureKey: string) {
    localStorage.setItem(featureKey, RateService.done);
  }

  public isRated(featureKey: string = RateService.app) {
    return localStorage.getItem(featureKey) == RateService.done;
  }

  public removeRate(featureKey: string = RateService.app) {
    return localStorage.removeItem(featureKey);
  }
}
