/**
 * Made by mkcomponent.sh
*/

import { Component, OnInit, Inject, Input, PLATFORM_ID, Output, EventEmitter }    from '@angular/core'
import { isPlatformBrowser } from '@angular/common'
import { Router, ActivatedRoute }       from '@angular/router'
import { TransferState, makeStateKey } from '@angular/platform-browser'


import { AppHelper }                    from '@k-settings/app-helper'
import { UserService }                  from '../../services/svc.user'
import { RestrictedCmsService }         from '../../services/svc.restricted-cms'
import { SharedService } from '@k-services/svc.shared'
import { LocalstorageService } from '@k-core/services/general/storage'

const loginPageKey = makeStateKey('LoginPageStateKey')

@Component({
    moduleId: module.id+ '',
    selector: 'user-login',
    templateUrl: './tpl.login.pug',
    styleUrls: ['sty.login.scss']
})

export class loginComponent implements OnInit {

    // Variables
    @Input('location') location: string
    @Output('status') status = new EventEmitter

    returnUrl: string;
    message: string;
    content: any;


    constructor(
        @Inject(PLATFORM_ID) private _platformId,
        public localStorage: LocalstorageService,
        private _shared: SharedService,
        private _user: UserService,
        private _restricted: RestrictedCmsService,
        private _router: Router,
        private _state: TransferState,
        private _route: ActivatedRoute
    ) { }

    // Lifehooks

    ngOnInit() {
        this.returnUrl = this._route.snapshot.queryParams['returnUrl'] ||  '/';

        this.content = this._state.get(loginPageKey, null as any)

        if(!this.content) {

            this._restricted.getPageContent('login').then((response) => {
                this.content = response.content
                this._state.set(loginPageKey, this.content as any)
            })
        }

        if(isPlatformBrowser(this._platformId)) {

            if(this.localStorage.getItem('user-key')) {

                this.status.emit('success')

                if(!!this.location) {

                    this._router.navigate([this.location])
                } else {

                    this._router.navigate(['/'])
                }

            } else {
                this.status.emit('error')
            }
        }
    }

    // Functions
    /**
     * Verifies and submits the user if valid, else responds with error as `message`
     * 
     * @param form 
     */
    submitUser(form) {

        this._user.verify(form.value).then(response => {

            if(response == 'success') {

                this.status.emit(response)
                this._shared.setPageState(true)

                this._router.navigate([this.returnUrl]);
            }
            else {

                this.status.emit(response)

                this.message = response
            }
        })
    }


}