/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Component} from '@angular/core';
import {
  SCFeedbackRequest,
  SCFeedbackRequestMetaData,
  SCMessage,
  SCPersonWithoutReferences,
  SCThingOriginType,
  SCThingType,
} from '@openstapps/core';
import {DataProvider} from '../data/data.provider';
import {DebugDataCollectorService} from '../data/debug-data-collector.service';
import {AlertController, ToastController} from '@ionic/angular/standalone';
import {TranslateService} from '@ngx-translate/core';

@Component({
  templateUrl: './feedback-page.html',
  styleUrls: ['./feedback-page.scss'],
})
export class FeedbackPageComponent {
  /**
   * Minimum allowed size of the feedback message
   */
  MINIMUM_MESSAGE_SIZE = 15;

  constructor(
    private readonly dataProvider: DataProvider,
    private readonly debugDataCollector: DebugDataCollectorService,
    private readonly toastController: ToastController,
    private readonly alertController: AlertController,
    private readonly translateService: TranslateService,
  ) {}

  /**
   * Sender of the feedback message
   */
  author: SCPersonWithoutReferences = {
    uid: '0f53f16a-e618-5ae0-a1b6-336e34f0d4d1',
    name: '',
    type: SCThingType.Person,
  };

  /**
   * The message to be sent
   */
  message: SCMessage = {
    uid: '0f53f16a-e618-5ae0-a1b6-336e34f0d4d1',
    name: 'Bug',
    type: SCThingType.Message,
    audiences: [],
    categories: [],
    origin: {
      type: SCThingOriginType.User,
      created: new Date().toISOString(),
    },
    messageBody: '',
  };

  /**
   * Terms of feedback accepted or not
   */
  termsAgree = false;

  /**
   * Providing of protocol data accepted or not
   */
  protocolDataAgree = false;

  /**
   * Show meta data or not
   */
  showMetaData = false;

  /**
   * Feedback successfully sent
   */
  submitSuccess = false;

  /**
   * Terms of feedback accepted or not
   */
  metaData: SCFeedbackRequestMetaData;

  async ionViewDidEnter() {
    this.metaData = await this.debugDataCollector.getFeedbackMetaData();
  }

  /**
   * Assemble and send the feedback
   */
  async onSubmit() {
    if (this.author.name !== '') {
      this.message.authors = [this.author];
    }

    const feedbackRequest: SCFeedbackRequest = {
      ...this.message,
      metaData: {
        platform: '',
        scope: {},
        state: {},
        userAgent: '',
        version: '',
      },
    };
    if (this.protocolDataAgree) {
      feedbackRequest.metaData = this.metaData;
    }

    try {
      await this.dataProvider.sendFeedback(feedbackRequest);
      void this.onSuccess();
    } catch {
      void this.onError();
    }
  }

  /**
   * Show/hide the meta data
   */
  toggleShowMetaData() {
    this.showMetaData = !this.showMetaData;
  }

  async onSuccess() {
    this.submitSuccess = true;
    const toast = await this.toastController.create({
      message: this.translateService.instant('feedback.system_messages.success'),
      duration: 2000,
      color: 'success',
    });
    await toast.present();
  }

  async onError() {
    const alert: HTMLIonAlertElement = await this.alertController.create({
      buttons: [this.translateService.instant('app.ui.CLOSE')],
      header: this.translateService.instant('app.ui.ERROR'),
      message: this.translateService.instant('app.errors.UNKNOWN'),
    });

    await alert.present();
  }
}
