/**
 * Display handler for rudder input.
 * 
 * @category Webserver
 * @package ATProcessor
 * @author Sam Meredith <sam@aandtinstruments.com>
 * @version 0.1
 * 
 */

class SavedConfigurationModel extends ObservableModel
{
    constructor()
    {
        super();
    }

    init()
    {

    }

    persistData()
    {

    }
}

class SavedConfigurationController extends BasicController
{
    constructor(model)
    {
        super(model);
    }

    deleteConfiguration(filename)
    {
        $.ajax( {
            url: '/helpers.php',
            type: 'POST',
            data:
            {
                'action': 'deleteConfiguration', 
                'filename': filename,
            },
            success: function()
            {
                // Just reload the page to repopulate the file list
                location.reload();
            }
        });
    }

    factoryReset()
    {
        $.ajax({
            url: '/helpers.php',
            type: 'POST',
            data:
            {
                'action': 'alertProcessor',
                'alert': 'Reset'
            },
            success: function(response)
            {
                $('#dialog-text').html('Factory Reset Started');
                $('#dialog').dialog( {
                    title: "Factory Reset",
                    buttons: {}
                }).dialog( "open" );

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Deleting old configuration');
                }, 1000);

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Restoring factory defaults');
                }, 3000);

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Waiting for database...');
                }, 10000);

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Restarting Processor');
                }, 15000);

                setTimeout(function()
                {
                    location.reload();
                }, 20000);
            }
        });
    }

    restoreConfiguration(configurationName)
    {
        $.ajax({
            url: '/helpers.php',
            type: 'POST',
            data:
            {
                'action': 'alertProcessor',
                'alert': 'Restore&BackupName=' + configurationName,
            },
            success: function(response)
            {
                $('#dialog-text').html('Configuration Restore Started');
                $('#dialog').dialog( {
                    title: "Restore from File",
                    buttons: {}
                }).dialog( "open" );

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Deleting old configuration');
                }, 1000);

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Restoring new configuration');
                }, 3000);

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Waiting for database...');
                }, 10000);

                setTimeout(function()
                {
                    $('#dialog-text').append('<br><br>Restarting Processor');
                }, 15000);

                setTimeout(function()
                {
                    location.reload();
                }, 20000);
            }
        });
    }

    restoreFromFile(formData, filename)
    {
        let self = this;

        $.ajax(
        {
            url: 'upload.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            cache: false

        }).done(function()
        {
            self.restoreConfiguration(filename);
        });
    }

    saveConfiguration(configurationName)
    {
        $.ajax({
			url: '/helpers.php',
			type: 'POST',
			data: {
				'action': 'alertProcessor', 
				'alert': 'Backup&BackupName=' + configurationName, 
			},
			success: function()
            {
				$('#dialog-text').text('Configuration saved successfully.');
				$('#dialog').dialog(
                {
					title:"Configuration Saved",
					buttons: {
						Ok: function()
                        {
							$(this).dialog("close");

                            // Rather than attempt to repopulate the configuration list, just reload the page
							location.reload();
						}
					},
				}).dialog("open");
			}
		});
    }
}

class SavedConfigurationView extends BasicView
{
    constructor(controller)
    {
        super(controller);

        $('#save-configuration-name').inputmask({
            regex: "[0-9a-zA-Z_]+"
        });

        this.controller.model.init();
    }

    bindEvents()
    {
        super.bindEvents();

        $('#configuration-select').on('change', this.onChangeConfiguration);
        $('#delete').on('click', this.onDeleteClicked.bind(this));
        $('#factory-reset-button').on('click', this.onFactoryResetClick.bind(this));
        $('#restore').on('click', this.onRestoreClicked.bind(this));
        $('#save').on('click', this.onSaveClicked.bind(this));
        $('#upload-form').on('submit', this.onRestoreFromFile.bind(this));
    }

    onChangeConfiguration(e)
    {
        // NOTE: SQLite expects timestamp in seconds, JS date functions expect milliseconds
        var date = new Date(parseInt($('#configuration-select option:selected').attr('data-timestamp') * 1000));

		$('#configuration-date').val(date.toDateString());

		if ($(e.target).find(':selected').val() != "")
        {
			let fileString = "/logs/database/" + $(e.target).find(':selected').val();
			$('#export').attr('href', fileString).show();
		}
		else
        {
			$('#export').removeAttr("href");
			$('#configuration-date').val("");
		}
    }

    onDeleteClicked(e)
    {
        let filename = "logs/database/" + $('#configuration-select :selected').val();
        let self = this;
    
		$('#dialog-text').text('Are you sure you want to delete the selected configuration?');
		$('#dialog').dialog({
			title: 'Are you sure?',
			buttons:
            {
				Ok : function()
                {
					$(this).dialog("close");
                    self.controller.deleteConfiguration(filename);
				},
				Cancel : function()
                {
					$(this).dialog("close");
				}
			}
		}).dialog("open");
    }

    onFactoryResetClick(e)
    {
        let self = this;

        $('#dialog-text').text('Are you sure you want to reset all configurations to the factory defaults?');
		$('#dialog').dialog(
        {
			title: "Are you sure?",
			buttons:
            {
				Ok: function()
                {
					$(this).dialog("close");
                    self.controller.factoryReset();
				},
				Cancel: function()
                {
					$(this).dialog("close");
					return;
				}
			}
		}).dialog("open");
    }

    onRestoreClicked(e)
    {
        let filename = $('#configuration-select :selected').val();	

		if (filename == "")
        {
			$('#dialog-text').text('Select a configuration to restore.');
			$('#dialog').dialog({
				title: 'No Configuration',
				buttons:
                {
					Ok: function()
                    {
						$(this).dialog("close");
					}
				}
			}).dialog("open");
		}
        else
        {
            this.controller.restoreConfiguration(filename);
		}
    }

    onRestoreFromFile(e)
    {
        e.preventDefault();

		if ($('#fileToUpload').prop('files').length == 0)
        {
			$('#dialog-text').text('Please select configuration file to recover.');
			$('#dialog').dialog(
            {
				title: "No File",
				buttons: {
					Ok : function() 
                    {
						$(this).dialog("close");
					}
				}
			}).dialog( "open" );
		}
        else
        {
            let fileName = $('#fileToUpload')[0].files[0].name;
            let regex = RegExp('^[0-9a-zA-Z_]+\.dbbackup$', 'g');

            if (regex.test(fileName)) 
            {
                const match = fileName.match(/(.*)_(\d+)_(\d+)_(\d+).*\.dbbackup$/);
                if (match)
                {
                    var formData = new FormData(e.target);
                    formData.append('action', 'Configuration');

                    this.controller.restoreFromFile(formData, fileName);
                }
                else
                {
                    $('#dialog-text').text("Unexpected file. Expect format <name>_<day>_<month>_<year>");
                    $('#dialog').dialog(
                    {
                        title: "Unexpected File",
                        buttons: 
                        {
                            Ok: function() 
                            {
                                $(this).dialog("close");
                            }
                        }
                    }).dialog("open");
                }
            } 
            else 
            {
                $('#dialog-text').text("Unexpected file. Expect a .dbbackup file with a name consisting of letters, numbers and undercores only.");
                $('#dialog').dialog(
                {
                    title: "Unexpected File",
                    buttons:
                    {
                        Ok: function()
                        {
                            $(this).dialog("close");
                        }
                    }
                }).dialog("open");
            }
		}
    }

    onSaveClicked(e)
    {
        // Check name is valid
        let configurationName = $('#save-configuration-name').val();
        if (!/^(?:\w+\s*)+$/.test(configurationName))
        {
			$('#save-configuration-name').focus().select();

			$('#dialog-text').text('Configuration name can contain alphanumeric characters, underscores and spaces only.');
			$('#dialog').dialog({
				title: "Invalid Name",
				buttons: {
					Ok: function() {
						$(this).dialog("close");
					}
				}
			}).dialog("open");

			return false;
		}

        this.controller.saveConfiguration(configurationName);
    }

    update(model)
    {

    }
}