//
//  ChartViewController.swift
//  NeoSpectraSwift
//
//  Created by doda on 10/24/16.
//  Copyright © 2016 siware. All rights reserved.
//

import UIKit
import Charts
import MessageUI
//import FileBrowser

class ChartViewController: UIViewController, MFMailComposeViewControllerDelegate {
    
    var doubledata: [[Double]] = [[Double]]()
    var floatdata: [Float] = [Float]()
    var source: String?
    var timer            : Timer?
    var saveExportName: String?
    
    let Colors = [UIColor.init(red: 0/255, green: 0/255, blue: 255/255, alpha: 1),
                  UIColor.init(red: 255/255, green: 20/255, blue: 147/255, alpha: 1),
                  UIColor.init(red: 255/255, green: 215/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 0/255, green: 255/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 0/255, green: 128/255, blue: 128/255, alpha: 1),
                  UIColor.init(red: 106/255, green: 90/255, blue: 205/255, alpha: 1),
                  UIColor.init(red: 210/255, green: 105/255, blue: 30/255, alpha: 1),
                  UIColor.init(red: 154/255, green: 205/255, blue: 50/255, alpha: 1),
                  UIColor.init(red: 0/255, green: 255/255, blue: 255/255, alpha: 1),
                  UIColor.init(red: 255/255, green: 140/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 139/255, green: 0/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 124/255, green: 252/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 138/255, green: 43/255, blue: 226/255, alpha: 1),
                  UIColor.init(red: 105/255, green: 105/255, blue: 105/255, alpha: 1),
                  UIColor.init(red: 102/255, green: 205/255, blue: 170/255, alpha: 1),
                  UIColor.init(red: 255/255, green: 69/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 0/255, green: 0/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 106/255, green: 90/255, blue: 205/255, alpha: 1),
                  UIColor.init(red: 255/255, green: 255/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 50/255, green: 205/255, blue: 50/255, alpha: 1),
                  UIColor.init(red: 25/255, green: 25/255, blue: 112/255, alpha: 1),
                  UIColor.init(red: 255/255, green: 0/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 128/255, green: 128/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 139/255, green: 69/255, blue: 19/255, alpha: 1),
                  UIColor.init(red: 148/255, green: 0/255, blue: 211/255, alpha: 1),
                  UIColor.init(red: 0/255, green: 100/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 47/255, green: 79/255, blue: 79/255, alpha: 1),
                  UIColor.init(red: 178/255, green: 34/255, blue: 34/255, alpha: 1),
                  UIColor.init(red: 30/255, green: 144/255, blue: 255/255, alpha: 1),
                  UIColor.init(red: 0/255, green: 128/255, blue: 0/255, alpha: 1),
                  UIColor.init(red: 255/255, green: 105/255, blue: 180/255, alpha: 1)]
    
    @IBOutlet weak var chartSwitch: UISegmentedControl!
    @IBOutlet weak var yAxisChartSwitch: UISegmentedControl!
    @IBOutlet weak var yAxisLabel: UILabel!
    @IBOutlet weak var lineChartView: LineChartView!
    @IBOutlet weak var ExportSaveButton: UIBarButtonItem!
    
    @IBAction func captureButtonTapped(_ sender: Any) {
        if(self.source == "PSD"){
            Constants.PSDcaptureRequested = true
        }else if(self.source == "Spectrum"){
            Constants.SpectrumcaptureRequested = true
        }
    }
    @IBAction func clearGraphButtonTapped(_ sender: Any) {
        if(self.source == "PSD"){
            Constants.PSDdoubledata = [[Double]]()
            Constants.PSDstartingDataCount = 0
        }else if(self.source == "Spectrum"){
            Constants.Spectrumdoubledata = [[Double]]()
            Constants.SpectrumstartingDataCount = 0
        }
    }
    @IBAction func cancelButtonTapped(_ sender: AnyObject) {
        self.timer?.invalidate()
        self.timer = nil
        self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func switchValueChanges(_ sender: AnyObject) {
        setChartData(index: chartSwitch.selectedSegmentIndex)
    }
    
    @IBAction func yAxisSwitchValueChanges(_ sender: Any) {
        setChartData(index: chartSwitch.selectedSegmentIndex)
    }
    @IBAction func Export_SaveButtonTapped(_ sender: AnyObject) {
        /*
        // text to share
        let text = "This is some text that I want to share."
        
        // set up activity view controller
        let textToShare = [ text ]
        let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
        
        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]
        
        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)
         */
        if(self.doubledata.count > 0){
            let alertController = UIAlertController(title: "Export spectra", message:
                "Select how you would like to export the spectra.", preferredStyle: UIAlertControllerStyle.alert)
            
            alertController.addAction(UIAlertAction(title: "Share by Mail", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
                self.getName(requestedAction: 1)
            }))
            
            alertController.addAction(UIAlertAction(title: "Save in App", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
                self.getName(requestedAction: 2)
            }))
            alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
            
            DispatchQueue.main.async {
                self.present(alertController, animated: true, completion: nil)
            }
        }else{
            let alertController = UIAlertController(title: "Export spectra", message:
                "No Data to be exported or saved.", preferredStyle: UIAlertControllerStyle.alert)
            
            alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
            
            DispatchQueue.main.async {
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }
    
    func getName(requestedAction: Int){
        let alertController = UIAlertController(title: "Export spectra", message:
            "Please enter the file name.", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addTextField { (configurationTextField) in
            //configure here your textfield
            configurationTextField.placeholder = "Measurement"
            configurationTextField.textColor = UIColor.black
            configurationTextField.keyboardType = UIKeyboardType.namePhonePad
        }
        
        alertController.addAction(UIAlertAction(title: "Set", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
            let textField = (alertController.textFields?.first)! as UITextField
            if(textField.text == "" && requestedAction == 1){
                self.saveExportName = "Measurement"
                self.ExportbyMail()
            }else if(textField.text == "" && requestedAction == 2){
                self.saveExportName = "Measurement"
                self.SaveData()
            }else if(requestedAction == 1){
                self.saveExportName = textField.text!
                self.ExportbyMail()
            }else if(requestedAction == 2){
                self.saveExportName = textField.text!
                self.SaveData()
            }
        }))
        
        alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler:nil))
        
        DispatchQueue.main.async {
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    func ExportbyMail(){
        if( MFMailComposeViewController.canSendMail() ) {
            let mailComposer = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self
            mailComposer.setSubject(self.saveExportName!)
            mailComposer.setMessageBody(self.saveExportName!, isHTML: false)
            
            var fileExtension = ""
            var fileHeader = ""
            var nameExtra = ""
            if(self.source == "PSD"){
                fileExtension = ".InterPSD"
                if(self.chartSwitch.selectedSegmentIndex == 0){
                    fileHeader = "x_Axis:Wavelength (nm)\ty_Axis:PSD (a.u.)"
                }else{
                    fileHeader = "x_Axis:Wavenumber (cm-1)\ty_Axis:PSD (a.u.)"
                }
            }else if(self.source == "Spectrum"){
                fileExtension = ".Spectrum"
                if(self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 0){
                    fileHeader = "x_Axis:Wavelength (nm)\ty_Axis:%Reflectance or Transmittance"
                    nameExtra = "_Perc"
                }else if(self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 0){
                    fileHeader = "x_Axis:Wavenumber (cm-1)\ty_Axis:%Reflectance or Transmittance"
                    nameExtra = "_Perc"
                }else if(self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                    fileHeader = "x_Axis:Wavelength (nm)\ty_Axis:Absorbance"
                    nameExtra = "_Abs"
                }else if(self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                    fileHeader = "x_Axis:Wavenumber (cm-1)\ty_Axis:Absorbance"
                    nameExtra = "_Abs"
                }
            }
            
            for i in 0 ..< doubledata.count{
                var file = ""
                if(self.source == "PSD"){
                    file = String.init(format: self.saveExportName! + "_" + String(i + 1) + fileExtension)
                }else{
                    file = String.init(format: self.saveExportName! + nameExtra + "_" + String(i + 1) + fileExtension)
                }
                
                var textOfFile = fileHeader
                let length = doubledata[i].count / 2
                for j in 0..<doubledata[i].count / 2{
                    if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                        textOfFile += String.init(format: "\n%@\t%@", String(10000000/doubledata[i][doubledata[i].count - j - 1]), String(-(log10(doubledata[i][length - j - 1] / 100))))
                    }else if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                        textOfFile += String.init(format: "\n%@\t%@", String(doubledata[i][j + length]), String(-(log10(doubledata[i][j] / 100))))
                    }else if(self.chartSwitch.selectedSegmentIndex == 0){
                        textOfFile += String.init(format: "\n%@\t%@", String(10000000/doubledata[i][doubledata[i].count - j - 1]), String(doubledata[i][length - j - 1]))
                    }else if(self.chartSwitch.selectedSegmentIndex == 1){
                        textOfFile += String.init(format: "\n%@\t%@", String(doubledata[i][j + length]), String(doubledata[i][j]))
                    }
                }
                
                if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first {
                    let path = URL(fileURLWithPath: dir).appendingPathComponent(self.saveExportName! + "_" + file)
                    do {
                        try textOfFile.write(to: path, atomically: false, encoding: String.Encoding.utf8)
                    }
                    catch {/* error handling here */}
                    mailComposer.addAttachmentData(try! Data(contentsOf: path), mimeType: "text/strings", fileName: file)
                    do{
                        try FileManager.default.removeItem(at: path)
                    }
                    catch{}
                }
            }
            self.present(mailComposer, animated: true, completion: nil)
            
        }
    }
    
    func SaveData(){
        let fileBrowser = FileBrowser(save_load: "save")
        fileBrowser.excludesFileExtensions = ["InterPSD", "Spectrum"]
        fileBrowser.setChartView(chartView: self)
        present(fileBrowser, animated: true, completion: nil)
    }
    
    func saveDataLogic(path: URL){
        var fileExtension = ""
        var fileHeader = ""
        var nameExtra = ""
        if(self.source == "PSD"){
            fileExtension = ".InterPSD"
            if(self.chartSwitch.selectedSegmentIndex == 0){
                fileHeader = "x_Axis:Wavelength (nm)\ty_Axis:PSD (a.u.)"
            }else{
                fileHeader = "x_Axis:Wavenumber (cm-1)\ty_Axis:PSD (a.u.)"
            }
        }else if(self.source == "Spectrum"){
            fileExtension = ".Spectrum"
            if(self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 0){
                fileHeader = "x_Axis:Wavelength (nm)\ty_Axis:%Reflectance or Transmittance"
                nameExtra = "_Perc"
            }else if(self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 0){
                fileHeader = "x_Axis:Wavenumber (cm-1)\ty_Axis:%Reflectance or Transmittance"
                nameExtra = "_Perc"
            }else if(self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                fileHeader = "x_Axis:Wavelength (nm)\ty_Axis:Absorbance"
                nameExtra = "_Abs"
            }else if(self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                fileHeader = "x_Axis:Wavenumber (cm-1)\ty_Axis:Absorbance"
                nameExtra = "_Abs"
            }
        }
        
        var rememberOverWrite = -1
        for i in 0 ..< doubledata.count{
            var file = ""
            if(self.source == "PSD"){
                file = String.init(format: self.saveExportName! + "_" + String(i + 1) + fileExtension)
            }else{
                file = String.init(format: self.saveExportName! + nameExtra + "_" + String(i + 1) + fileExtension)
            }
            
            let fullPath = path.appendingPathComponent(file)
            if(FileManager.default.fileExists(atPath: fullPath.path)){
                if(rememberOverWrite == -1){
                    let alertController = UIAlertController(title: "Overwrite", message:
                        "The chosen directory has files with the same name, overwrite all?", preferredStyle: UIAlertControllerStyle.alert)
                    
                    alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
                        rememberOverWrite = 1
                        
                        var textOfFile = fileHeader
                        let length = self.doubledata[i].count / 2
                        for j in 0..<self.doubledata[i].count / 2{
                            if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                                textOfFile += String.init(format: "\n%@\t%@", String(10000000/self.doubledata[i][self.doubledata[i].count - j - 1]), String(-(log10(self.doubledata[i][length - j - 1] / 100))))
                            }else if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                                textOfFile += String.init(format: "\n%@\t%@", String(self.doubledata[i][j + length]), String(-(log10(self.doubledata[i][j] / 100))))
                            }else if(self.chartSwitch.selectedSegmentIndex == 0){
                                textOfFile += String.init(format: "\n%@\t%@", String(10000000/self.doubledata[i][self.doubledata[i].count - j - 1]), String(self.doubledata[i][length - j - 1]))
                            }else if(self.chartSwitch.selectedSegmentIndex == 1){
                                textOfFile += String.init(format: "\n%@\t%@", String(self.doubledata[i][j + length]), String(self.doubledata[i][j]))
                            }
                        }
                        
                        let filePath = URL(fileURLWithPath: path.absoluteString).appendingPathComponent(file)
                        do {
                            try textOfFile.write(to: filePath, atomically: false, encoding: String.Encoding.utf8)
                        }
                        catch {/* error handling here */}
                    }))
                    
                    alertController.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: { (UIAlertAction) in
                        rememberOverWrite = 0
                    }))
                    
                    DispatchQueue.main.async {
                        self.present(alertController, animated: true, completion: nil)
                    }
                }else if(rememberOverWrite == 1){
                    var textOfFile = fileHeader
                    let length = doubledata[i].count / 2
                    for j in 0..<doubledata[i].count / 2{
                        if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                            textOfFile += String.init(format: "\n%@\t%@", String(10000000/doubledata[i][doubledata[i].count - j - 1]), String(-(log10(doubledata[i][length - j - 1] / 100))))
                        }else if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                            textOfFile += String.init(format: "\n%@\t%@", String(doubledata[i][j + length]), String(-(log10(doubledata[i][j] / 100))))
                        }else if(self.chartSwitch.selectedSegmentIndex == 0){
                            textOfFile += String.init(format: "\n%@\t%@", String(10000000/doubledata[i][doubledata[i].count - j - 1]), String(doubledata[i][length - j - 1]))
                        }else if(self.chartSwitch.selectedSegmentIndex == 1){
                            textOfFile += String.init(format: "\n%@\t%@", String(doubledata[i][j + length]), String(doubledata[i][j]))
                        }
                    }
                    
                    let filePath = URL(fileURLWithPath: path.absoluteString).appendingPathComponent(file)
                    do {
                        try textOfFile.write(to: filePath, atomically: false, encoding: String.Encoding.utf8)
                    }
                    catch {/* error handling here */}
                }
            }else{
                var textOfFile = fileHeader
                let length = doubledata[i].count / 2
                for j in 0..<doubledata[i].count / 2{
                    if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 0 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                        textOfFile += String.init(format: "\n%@\t%@", String(10000000/doubledata[i][doubledata[i].count - j - 1]), String(-(log10(doubledata[i][length - j - 1] / 100))))
                    }else if(self.source == "Spectrum" && self.chartSwitch.selectedSegmentIndex == 1 && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                        textOfFile += String.init(format: "\n%@\t%@", String(doubledata[i][j + length]), String(-(log10(doubledata[i][j] / 100))))
                    }else if(self.chartSwitch.selectedSegmentIndex == 0){
                        textOfFile += String.init(format: "\n%@\t%@", String(10000000/doubledata[i][doubledata[i].count - j - 1]), String(doubledata[i][length - j - 1]))
                    }else if(self.chartSwitch.selectedSegmentIndex == 1){
                        textOfFile += String.init(format: "\n%@\t%@", String(doubledata[i][j + length]), String(doubledata[i][j]))
                    }
                }
                
                let filePath = URL(fileURLWithPath: path.absoluteString).appendingPathComponent(file)
                do {
                    try textOfFile.write(to: filePath, atomically: false, encoding: String.Encoding.utf8)
                }
                catch {/* error handling here */}
            }
        }
    }
    
    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        self.dismiss(animated: true, completion: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView else { return }
        statusBar.backgroundColor = UIColor.clear
        
        self.navigationController?.setToolbarHidden(false, animated: true)
        
        self.ExportSaveButton.isEnabled = false
        lineChartView.noDataText = "You need to provide data for the chart."
        chartSwitch.setTitle("nm", forSegmentAt: 0)
        chartSwitch.setTitle("cm\u{FE58}\u{00B9}", forSegmentAt: 1)
        yAxisChartSwitch.setTitle("%", forSegmentAt: 0)
        yAxisChartSwitch.setTitle("Abs.", forSegmentAt: 1)
        if(self.source == "PSD"){
            self.yAxisChartSwitch.isHidden = true
            self.yAxisLabel.isHidden = true
        }
        setChartData(index: 0)
        self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.timerFire), userInfo: nil, repeats: true)
    }
    
    private var _orientations = UIInterfaceOrientationMask.landscape
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
        get { return self._orientations }
        set { self._orientations = newValue }
    }
    
    func reportError(){
        let alertController = UIAlertController(title: "Error", message:
            String(format: "Error number: %d" , Constants.reportedError), preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
        DispatchQueue.main.async {
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    @objc func timerFire() {
        if(self.source == "PSD"){
            self.doubledata = Constants.PSDdoubledata
        }else if(self.source == "Spectrum"){
            self.doubledata = Constants.Spectrumdoubledata
        }
        if(Constants.reportedError != 0){
            self.reportError()
            Constants.reportedError = 0
        }
        if(Constants.kitInUsePSD || Constants.kitInUseSpectrum){
            self.ExportSaveButton.isEnabled = false
        }else{
            self.ExportSaveButton.isEnabled = true
        }
        self.setChartData(index: chartSwitch.selectedSegmentIndex)
    }
    
    func setChartData(index: Int) -> Void
    {
        var yVals1 : [[ChartDataEntry]] = [[ChartDataEntry]]()
        var sets : [LineChartDataSet] = [LineChartDataSet]()
        
        if(self.doubledata.count > 0){
            if(index == 1){
                yVals1 = chartDataForNotLamda()
            }else{
                yVals1 = chartDataForLamda()
            }
            var colorsIteration = 0
            for i in 0..<doubledata.count{
                let set = LineChartDataSet(values: yVals1[i], label:"Mt. No." + String(colorsIteration + 1))
                set.axisDependency = .left // Line will correlate with left axis values
                set.setColor(self.Colors[colorsIteration])
                set.setCircleColor(self.Colors[colorsIteration])
                set.lineWidth = 2.0
                set.circleRadius = 1.0
                set.fillAlpha = 65 / 255.0
                set.fillColor = UIColor.red
                set.highlightColor = UIColor.white
                set.drawCircleHoleEnabled = false
                sets.append(set)
                colorsIteration += 1
                if(colorsIteration == self.Colors.count){
                    colorsIteration = 0
                }
            }
        }else{
            if(index == 1){
                yVals1 = dummyDataForNotLamda()
            }else{
                yVals1 = dummyDataForLamda()
            }
            
            let set = LineChartDataSet(values: yVals1[0], label:"")
            set.axisDependency = .left // Line will correlate with left axis values
            set.setColor(UIColor.clear)
            set.setCircleColor(UIColor.clear)
            set.lineWidth = 2.0
            set.circleRadius = 1.0
            set.fillAlpha = 65 / 255.0
            set.fillColor = UIColor.red
            set.highlightColor = UIColor.white
            set.drawCircleHoleEnabled = false
            set.drawValuesEnabled = false
            sets.append(set)
        }
        //var dataSets : [LineChartDataSet] = [LineChartDataSet]()
        //for j in 0..<doubledata.count{
        //    dataSets.append(sets[j])
        //}
        
        let data: LineChartData = LineChartData(dataSets: sets)
        
        self.lineChartView.data = data
    }
    
    func chartDataForNotLamda() -> [[ChartDataEntry]]{
        var yValsTotal : [[ChartDataEntry]] = [[ChartDataEntry]]()
        //var xVals = UserUtils.getWaveNumber()
        
        if floatdata.count > 0{
            //for i in 0 ..< floatdata.count {
            //    yVals1.append(ChartDataEntry(x: Double(xVals[i]), y: Double(floatdata[i])))
            //}
            
        }
        else{
            for i in 0 ..< doubledata.count {
                let length = doubledata[i].count / 2
                var yVals: [ChartDataEntry] = [ChartDataEntry]()
                for j in 0..<doubledata[i].count / 2{
                    if(self.source == "Spectrum" && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                        yVals.append(ChartDataEntry(x: doubledata[i][j + length], y: (-(log10(doubledata[i][j] / 100))) ))
                    }else{
                        yVals.append(ChartDataEntry(x: doubledata[i][j + length], y: doubledata[i][j]))
                    }
                }
                yValsTotal.append(yVals)
            }
        }
        
        return yValsTotal
    }
    
    func chartDataForLamda() -> [[ChartDataEntry]]{
        var yValsTotal : [[ChartDataEntry]] = [[ChartDataEntry]]()
        //var xVals = UserUtils.getLambda()
        
        if floatdata.count > 0 {
            //for i in 0 ..< floatdata.count {
            //    yVals1.append(ChartDataEntry(x: Double(xVals[floatdata.count - i - 1]), y: Double(floatdata[floatdata.count - i - 1])))
            //}
            
        }
        else{
            for i in 0 ..< doubledata.count{
                let length = doubledata[i].count / 2
                var yVals: [ChartDataEntry] = [ChartDataEntry]()
                for j in 0..<doubledata[i].count / 2{
                    if(self.source == "Spectrum" && self.yAxisChartSwitch.selectedSegmentIndex == 1){
                        yVals.append(ChartDataEntry(x: (10000000/doubledata[i][doubledata[i].count - j - 1]), y: (-(log10(doubledata[i][length - j - 1] / 100))) ))
                    }else{
                        yVals.append(ChartDataEntry(x: (10000000/doubledata[i][doubledata[i].count - j - 1]), y: doubledata[i][length - j - 1]))
                    }
                }
                yValsTotal.append(yVals)
            }
        }
        
        return yValsTotal
        
    }
    
    func dummyDataForNotLamda()-> [[ChartDataEntry]]{
        var yValsTotal : [[ChartDataEntry]] = [[ChartDataEntry]]()
        var yVals: [ChartDataEntry] = [ChartDataEntry]()
        if(self.source == "Spectrum" && self.yAxisChartSwitch.selectedSegmentIndex == 0){
            yVals.append(ChartDataEntry(x:3700, y:90))
            yVals.append(ChartDataEntry(x:7795, y:110))
        }else{
            yVals.append(ChartDataEntry(x:3700, y:0))
            yVals.append(ChartDataEntry(x:7795, y:1.2))
        }
        yValsTotal.append(yVals)
        return yValsTotal
    }
    
    func dummyDataForLamda()-> [[ChartDataEntry]]{
        var yValsTotal : [[ChartDataEntry]] = [[ChartDataEntry]]()
        var yVals: [ChartDataEntry] = [ChartDataEntry]()
        if(self.source == "Spectrum" && self.yAxisChartSwitch.selectedSegmentIndex == 0){
            yVals.append(ChartDataEntry(x:1285, y:90))
            yVals.append(ChartDataEntry(x:2615, y:110))
        }else{
            yVals.append(ChartDataEntry(x:1285, y:0))
            yVals.append(ChartDataEntry(x:2615, y:1.2))
        }
        yValsTotal.append(yVals)
        return yValsTotal
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        
    }
    
}
