import {Component, OnInit} from '@angular/core';
import {Api} from '../../service/api';
import {NavController} from '@ionic/angular';
import {ActivatedRoute, Router} from '@angular/router';
import {Load} from '../../service/load';
import {Transfer} from '../../service/transfer';
import {DatePipe} from '@angular/common';

@Component({
    selector: 'v-env-change-model',
    templateUrl: './env-change-model.page.html',
    styleUrls: ['./env-change-model.page.scss'],
})
export class EnvChangeModelPage implements OnInit {

    constructor(public nav: NavController,
                private api: Api,
                private ac: ActivatedRoute,
                private load: Load,
                private tf: Transfer,
                private router: Router,
                private datepipe: DatePipe) {}

    controlConfig = [];
    ngOnInit() {
        this.init();
    }

    init() {
        this.controlConfig = [{id: 1, name: '', startDate: '', stopDate: '', on: '', off: ''}];
    }

    addModel() {
        const modelCount = this.controlConfig.length;
        this.controlConfig.push({id: modelCount + 1, name: '', startDate: '', stopDate: '', on: '', off: ''});
    }

    deleteModel(one) {
        const updateModel = this.controlConfig.filter(data => data.id !== one.id);
        this.controlConfig = updateModel;
        this.controlConfig.forEach((item, index) => item.id = index + 1);
    }

    saveModels() {
        this.controlConfig.forEach((item) => {
            item.on = this.formartTime(item.on);
            item.off = this.formartTime(item.off);
            item.startDate = this.formartDate(item.startDate);
            item.stopDate = this.formartDate(item.stopDate);
        });
        const query = '?changeModelCfg=' + JSON.stringify(this.controlConfig);
        // this.nav.navigateForward('', );
        // this.nav.navigateBack()
        // this.nav.navigateBack('', {changeModels: this.controlConfig});
        // this.router.navigate(['/tabs/tab-cfg'], { queryParams: { changeModelCfg: this.controlConfig } });
        this.nav.navigateBack('/tabs/tab-cfg' + query);
    }

    goBack() {
        this.nav.back();
    }

    formartTime(time) {
        return this.datepipe.transform(time, 'HH:mm');
    }

    formartDate(date) {
        return this.datepipe.transform(date, 'MM-dd');
    }
}
