//
//  ClaimPageMenuViewController.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 26.11.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class ClaimPageMenuViewController: ViewControllerWithMenu, CAPSPageMenuDelegate {
    
    private var viewControllers: [UIViewController]!
    var pageMenu : CAPSPageMenu?
    var parameters: [CAPSPageMenuOption]?
    var siebelAccount: SiebelAccount!
    var siebelAccountDataListNames: [String] = []
    var selectedFullDamage: FullDamage?
    var selectedClaim: Claim?
    var currentTabIndex : Int = 0
    var selectedSiebelAccountDataIndex : Int = 0
    
    func configureViews() {
        //    "claim_page_menu.label.create_service_claims" = "CREATE SERVICE CLAIMS";
        let barButtonItem = UIBarButtonItem(title: LS("claim_page_menu.label.create_repair_bureau"), style: .Plain, target: self, action: #selector(ClaimPageMenuViewController.createRB(_:)))
        
        barButtonItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(11), NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal)
        self.navigationItem.rightBarButtonItem = barButtonItem
    }
    
    func createRB(sender: UIBarButtonItem) {
        performSegueWithIdentifier("rb_creation", sender: "rb")
    }
    
    func createSC(sender: UIBarButtonItem) {
        performSegueWithIdentifier("rb_creation", sender: "sc")
    }
    
    func fillDataList() {
        for item in self.siebelAccount.siebelAccountDataList {
            siebelAccountDataListNames.append("\(item.assetNumber ?? "") \(item.deviceGroupName ?? "")")
        }
    }
    
    func getSiebelAccountRequest() {
        let request = GetProvidersRequest(accessToken: Facade.accessToken, clientId: Facade.clientId, serverId: Facade.serverId, abonentId: Facade.accountId)
        guard request.validateFields() else { return }
        self.processRequest(true)
        Facade.sharedInstance().getSiebelAccount(request.params, onSuccess: { (siebelAccount) in
            self.siebelAccount = siebelAccount
            (self.viewControllers[0] as! ClaimListViewController).siebelAccount = siebelAccount
            (self.viewControllers[0] as! ClaimListViewController).fillDataList()
            (self.viewControllers[1] as! ClaimListViewController).siebelAccount = siebelAccount
            (self.viewControllers[1] as! ClaimListViewController).fillDataList()
            self.fillDataList()
            if let firstItem = self.siebelAccount.siebelAccountDataList.first {
                (self.viewControllers[0] as! ClaimListViewController).currentSiebelAccountData = firstItem
                (self.viewControllers[1] as! ClaimListViewController).currentSiebelAccountData = firstItem
            }
            }, onError: { (error) in
                AlertViewUtil.showErrorAlert(error, vc: self)
        }) {
            self.processRequest(false)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureViews()
        //    localize()
        settingPaging()
        createViewControllers()
        getSiebelAccountRequest()
        
        pageMenu = CAPSPageMenu(viewControllers: viewControllers, frame: CGRectMake(0.0, 0.0, self.view.frame.width, self.view.frame.height), pageMenuOptions: parameters)
        
        // Lastly add page menu as subview of base view controller view
        // or use pageMenu controller in you view hierachy as desired
        self.view.addSubview(pageMenu!.view)
        pageMenu!.delegate = self
        pageMenu!.view.translatesAutoresizingMaskIntoConstraints = false
        let views = ["page_menu": pageMenu!.view]
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[page_menu]|", options: [], metrics: nil, views: views))
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[page_menu]|", options: [], metrics: nil, views: views))
    }
    
    func settingPaging() {
        parameters = [
            .UnselectedMenuItemLabelColor(UIColor.whiteColor().colorWithAlphaComponent(0.7)),
            .MenuItemSeparatorWidth(1),
            .UseMenuLikeSegmentedControl(true),
            .MenuItemSeparatorPercentageHeight(0.8),
            .ScrollMenuBackgroundColor(Color.DashboardBlueColor),
            .MenuItemSeparatorColor(UIColor.whiteColor().colorWithAlphaComponent(0.5)),
            .MenuItemFont(UIFont.systemFontOfSize(12)),
            .MenuHeight(44),
            CAPSPageMenuOption.SelectionIndicatorHeight(0)
        ]
    }
    
    func createViewControllers() {
        viewControllers = [UIViewController]()
        
        let claimListViewController = ClaimListViewController.fromStoryboard()
        claimListViewController.title = LS("claim_page_menu.label.repair_bureau")
        claimListViewController.vc = self
        claimListViewController.tabIndex = 0
        //    claimListViewController.cashAndPaymentsViewController = self
        viewControllers.append(claimListViewController)
        
        let claimListViewController2 = ClaimListViewController.fromStoryboard()
        claimListViewController2.title = LS("claim_page_menu.label.service_claims")
        claimListViewController2.vc = self
        claimListViewController2.tabIndex = 1
        //    claimListViewController.cashAndPaymentsViewController = self
        viewControllers.append(claimListViewController2)
        
        //    let paymentsHistoryViewController = storyboard!.instantiateViewControllerWithIdentifier("PaymentHistory")
        //      as! PaymentsHistoryViewController
        //    paymentsHistoryViewController.cashAndPaymentsViewController = self
        //    paymentsHistoryViewController.localize()
        //    viewControllers.append(paymentsHistoryViewController)
    }
    
    func reloadCurrentPage() {
        let viewController = viewControllers[currentTabIndex] as! ClaimListViewController
        viewController.requestSiebelData()
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        switch segue.identifier! {
        case "rb_creation":
            let vc = segue.destinationViewController as! RBCreationViewController
            vc.claimListVC = viewControllers[0] as! ClaimListViewController
            if (sender as? String) == "sc" {
                vc.claimCreationType = ClaimCreationType.SC
                //vc.selectedSiebelAccount = self.siebelAccount
                //vc.selectedDamageItem = self.selectedFullDamage
                
            } else {
                vc.claimCreationType = ClaimCreationType.RB
                //vc.selectedSiebelAccount = self.siebelAccount
                //vc.selectedClaimItem = self.selectedClaim
            }
            vc.vc = self
            break
        case Segue.FullDamageModal:
            let vc = segue.destinationViewController as! FullDamageModalViewController
            let currentIndex = sender as! Int
            currentTabIndex = currentIndex
            vc.tabIndex = currentIndex
            vc.vc = viewControllers[currentIndex] as! ClaimListViewController
            if currentIndex == 0 {
                vc.fullDamage = selectedFullDamage
            } else if currentIndex == 1 {
                vc.claim = selectedClaim
            }
            break
        default:
            break
        }
    }
    
}

// CAPSPageMenuDelegate
extension ClaimPageMenuViewController {
    func willMoveToPage(controller: UIViewController, index: Int) {
        
    }
    
    func didMoveToPage(controller: UIViewController, index: Int) {
        switch index {
        case 0:
            //    "claim_page_menu.label.create_service_claims" = "CREATE SERVICE CLAIMS"
            let barButtonItem = UIBarButtonItem(title: LS("claim_page_menu.label.create_repair_bureau"), style: .Plain, target: self, action: #selector(ClaimPageMenuViewController.createRB(_:)))
            barButtonItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(11), NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal)
            self.navigationItem.rightBarButtonItem = barButtonItem
            break
        case 1:
            let barButtonItem = UIBarButtonItem(title: LS("claim_page_menu.label.create_service_claims"), style: .Plain, target: self, action: #selector(ClaimPageMenuViewController.createSC(_:)))
            barButtonItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(11), NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal)
            self.navigationItem.rightBarButtonItem = barButtonItem
            break
        default:
            break
        }
        print("didMoveToPage")
    }
}

extension ClaimPageMenuViewController {
    override var localizedId: String {
        return "claim_page_menu"
    }
}
