// <auto-generated/>
#pragma warning disable 1591
#pragma warning disable 0414
#pragma warning disable 0649
#pragma warning disable 0169

namespace Analysis.Pages
{
    #line hidden
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
#nullable restore
#line 1 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using System.Net.Http;

#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using System.Net.Http.Json;

#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Microsoft.AspNetCore.Components;

#line default
#line hidden
#nullable disable
#nullable restore
#line 4 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Microsoft.AspNetCore.Components.Forms;

#line default
#line hidden
#nullable disable
#nullable restore
#line 5 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Microsoft.AspNetCore.Components.Routing;

#line default
#line hidden
#nullable disable
#nullable restore
#line 6 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Microsoft.AspNetCore.Components.Web;

#line default
#line hidden
#nullable disable
#nullable restore
#line 7 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Microsoft.AspNetCore.Components.WebAssembly.Http;

#line default
#line hidden
#nullable disable
#nullable restore
#line 8 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Microsoft.JSInterop;

#line default
#line hidden
#nullable disable
#nullable restore
#line 9 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Analysis;

#line default
#line hidden
#nullable disable
#nullable restore
#line 10 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Analysis.Shared;

#line default
#line hidden
#nullable disable
#nullable restore
#line 11 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Analysis.Models;

#line default
#line hidden
#nullable disable
#nullable restore
#line 12 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using Analysis.Services;

#line default
#line hidden
#nullable disable
#nullable restore
#line 13 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using System.Globalization;

#line default
#line hidden
#nullable disable
#nullable restore
#line 14 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using System.IO;

#line default
#line hidden
#nullable disable
#nullable restore
#line 15 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using System.Text.Json;

#line default
#line hidden
#nullable disable
#nullable restore
#line 16 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using System.Text;

#line default
#line hidden
#nullable disable
#nullable restore
#line 17 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\_Imports.razor"
using BlazorInputFile;

#line default
#line hidden
#nullable disable
    [Microsoft.AspNetCore.Components.RouteAttribute("/questions")]
    public partial class Calculator : Microsoft.AspNetCore.Components.ComponentBase
    {
        #pragma warning disable 1998
        protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
        {
        }
        #pragma warning restore 1998
#nullable restore
#line 647 "C:\Users\PawLie\Documents\Development\BTSM\Security\Analysis\Pages\Calculator.razor"
       
	private AnalysisModel analysisModel;
	private QuestionType? questionType;
	private bool showQuestions;
	private bool showTables;
	private bool showResult;
	private bool showErrorText;
	private string errorText;
	private string sectionTitle;
	private string questionTitle;
	private List<RatingTableModel> ratingTables;
	private List<SectionResultModel> sectionResults;
	private List<SectionResultCalculatedModel> calculatedResults;
	private List<ResultModel> results;
	private string resultTitle;

	protected override async Task OnInitializedAsync()
	{
		analysisModel = DataService.PrepareDefaultAnalysisModel();
		ratingTables = DataService.PrepareDefaultRatingTables();
		questionType = null;
		showQuestions = true;
		calculatedResults = new List<SectionResultCalculatedModel>();
		results = new List<ResultModel>();
	}

	private void setQuestionType(QuestionType? type = null)
	{
		questionType = type;
	}

	private void CheckChanged(QuestionModel question, int value)
	{
		foreach (var answ in question.Answers.Where(x => x.Value != value))
		{
			answ.IsChosen = false;
		}
	}

	private void QuestionEdit(QuestionModel model)
	{
		if (!string.IsNullOrEmpty(model.Question) && model.Edit)
			model.Edit = !model.Edit;
		else if(!model.Edit)
			model.Edit = !model.Edit;
	}

	private void AnswerEdit(AnswerModel model)
	{
		if (!string.IsNullOrEmpty(model.Answer) && model.Edit)
			model.Edit = !model.Edit;
		else if(!model.Edit)
			model.Edit = !model.Edit;
	}

	private void RatingEdit(RatingModel model)
	{
		model.Edit = !model.Edit;
	}

	private void AddPoint(List<AnswerModel> answers, AnswerModel answer)
	{
		if (answers.Any(x => x.Value == answer.Value + 1))
		{
			answers.FirstOrDefault(x => x.Value == answer.Value + 1).Value = answer.Value;
			answer.Value = answer.Value + 1;
		}
	}

	private void RemovePoint(List<AnswerModel> answers, AnswerModel answer)
	{
		if (answers.Any(x => x.Value == answer.Value - 1))
		{
			answers.FirstOrDefault(x => x.Value == answer.Value - 1).Value = answer.Value;
			answer.Value = answer.Value - 1;
		}
	}

	private void RemoveAnswer(List<AnswerModel> answers, AnswerModel answer)
	{
		foreach (var ans in answers.Where(x => x.Value > answer.Value))
		{
			ans.Value = ans.Value - 1;
		}
		answers.Remove(answer);
	}

	private void RemoveRating(List<RatingModel> ratings, RatingModel rating)
	{
		ratings.Remove(rating);
	}

	private void AddRating(List<RatingModel> ratings)
	{
		var rating = new RatingModel();
		rating.MinValue = ratings.LastOrDefault().MaxValue;
		rating.MaxValue = 100;
		rating.Edit = true;
		ratings.Add(rating);
	}

	private void RemoveQuestion(List<QuestionModel> questions, QuestionModel question)
	{
		if (questions.Count(x => x.QuestionType == question.QuestionType) < 2)
		{
			question.Question = string.Empty;
			question.Edit = true;
			question.Answers = new List<AnswerModel>();
			return;
		}
		questions.Remove(question);
	}

	private void AddAnswer(List<AnswerModel> answers, int lowestValue)
	{
		var value = 0;
		if (answers.Count == 0)
			value = lowestValue;
		else
			value = answers.Select(x => x.Value).DefaultIfEmpty().Max() + 1;
		var answer = new AnswerModel()
		{
			Value = value,
			Edit = true
		};
		answers.Add(answer);
	}

	private void AddQuestion(List<QuestionModel> questions, QuestionType? questionType = null)
	{
		var lowest = questions.Where(x => x.QuestionType == questionType).Select(x => x.LowestValue).DefaultIfEmpty().Max();
		var question = new QuestionModel()
		{
			QuestionType = questionType,
			Answers = new List<AnswerModel>(),
			Question = string.Empty,
			Edit = true,
			LowestValue = lowest
		};
		questions.Add(question);
	}

	private void ShowQuestions()
	{
		if (CheckRatingTables())
		{
			showErrorText = true;
			errorText = "Tabulky hodnot nejsou vyplněny správně";
			return;
		}
		errorText = string.Empty;
		showErrorText = false;
		showQuestions = true;
		showTables = false;
		showResult = false;
	}
	private void ShowTables()
	{
		if (CheckFilledQuestions())
		{
			showErrorText = true;
			errorText = "V některé z otázek chybí označena odpověď";
			return;
		}
		errorText = string.Empty;
		showErrorText = false;
		showQuestions = false;
		showTables = true;
		showResult = false;
	}
	private void ShowResult()
	{
		if (CheckFilledQuestions())
		{
			showErrorText = true;
			errorText = "V některé z otázek chybí označena odpověď";
			return;
		}
		if (CheckRatingTables())
		{
			showErrorText = true;
			errorText = "Tabulky hodnot nejsou vyplněny správně";
			return;
		}
		errorText = string.Empty;
		showErrorText = false;
		showQuestions = false;
		showTables = false;
		showResult = true;
	}

	private bool CheckFilledQuestions()
	{
		foreach (var section in analysisModel.Sections)
		{
			foreach (var question in section.Questions)
			{
				if (!question.Answers.Any(x => x.IsChosen))
				{
					return true;
				}
			}
		}
		return false;
	}

	private bool CheckRatingTables()
	{
		foreach (var ratingTable in ratingTables)
		{
			var lastMaxValue = 0;
			foreach (var rating in ratingTable.Ratings.OrderBy(x => x.MinValue))
			{
				if (rating.MinValue != lastMaxValue || rating.MaxValue > 100 || rating.MinValue > 100 || rating.MinValue > rating.MaxValue || string.IsNullOrEmpty(rating.Name) || rating.MaxValue == 0 || (lastMaxValue == 0 && rating.MinValue != 0) || rating.MinValue < 0 || rating.MaxValue < 0)
				{
					return true;
				}
				lastMaxValue = rating.MaxValue;
			}
			if (lastMaxValue != 100)
				return true;
		}
		return false;
	}

	private void ResetModel()
	{
		analysisModel = DataService.ClearAnalysisModel();
	}

	private void DefaultModel()
	{
		analysisModel = DataService.PrepareDefaultAnalysisModel();
	}

	private void ShowSection(SectionModel section)
	{
		section.ShowSection = !section.ShowSection;
	}

	private void ShowTable(RatingTableModel model)
	{
		model.ShowTable = !model.ShowTable;
	}

	private void SetSectionTitle(SectionType sectionType)
	{
		sectionTitle = GetSectionName(sectionType);
	}

	private string GetSectionName(SectionType sectionType)
	{
		if (sectionType == SectionType.InternalVulnerabilityCriteria)
			return "Interní kritéria zranitelnosti";
		else if (sectionType == SectionType.ExternalVulnerabilityCriteria)
			return "Externí kritéria zranitelnosti";
		else if (sectionType == SectionType.InternalSecurityCriteria)
			return "Interní kritéria bezpečnosti";
		else if (sectionType == SectionType.ExternalSecurityCriteria)
			return "Externí kritéria bezpečnosti";
		else if (sectionType == SectionType.OrganizationalSecurityAspects)
			return "Organizační aspekty bezpečnosti";
		else if (sectionType == SectionType.RegimeSecurityAspects)
			return "Režimové aspekty bezpečnosti";

		return string.Empty;
	}

	private void SetResultTitle(ResultType resultType)
	{
		if (resultType == ResultType.InternalVulnerabilityResult)
			resultTitle = "Hodnocení interní zranitelnosti";
		else if (resultType == ResultType.ExternalVulnerabilityResult)
			resultTitle = "Hodnocení externí zranitelnosti";
		else if (resultType == ResultType.VulnerabilityResult)
			resultTitle = "Hodnocení zranitelnosti";
		else if (resultType == ResultType.InternalSecurityResult)
			resultTitle = "Hodnocení interní bezpečnosti";
		else if (resultType == ResultType.ExternalSecurityResult)
			resultTitle = "Hodnocení externí bezpečnosti";
		else if (resultType == ResultType.OrganizationalRegimeResult)
			resultTitle = "Režimové a organizační aspekty bezpečnosti";
		else if (resultType == ResultType.SecurityResult)
			resultTitle = "Hodnocení bezpečnosti";
	}

	private void SetQuestionTitle(QuestionType? questionType)
	{
		questionTitle = GetQuestionName(questionType);
	}

	private string GetQuestionName(QuestionType? questionType)
	{
		if (questionType == QuestionType.ISpatialAspects || questionType == QuestionType.ESpatialAspects)
			return "Prostorové aspekty";
		else if (questionType == QuestionType.ITimeAspects || questionType == QuestionType.ETimeAspects)
			return "Časové aspekty";
		else if (questionType == QuestionType.IConcentrationPeople || questionType == QuestionType.EConcentrationPeople)
			return "Koncentrace a počet osob";
		else if (questionType == QuestionType.IStructuralMechanicalAspects || questionType == QuestionType.EStructuralMechanicalAspects)
			return "Strukturální a mechanické aspekty";
		else if (questionType == QuestionType.ITechnologicalProcessAspects || questionType == QuestionType.ETechnologicalProcessAspects)
			return "Technologické a procesní aspekty";
		else
			return string.Empty;
	}

	private int EditRatingValue(string value, List<RatingModel> ratings, bool isMinCheck, RatingModel rating)
	{
		var count = ratings.IndexOf(rating);

		var totalCount = ratings.Count;
		var intValue = Convert.ToInt32(value) < 0 ? 0 : Convert.ToInt32(value);
		ratings.FirstOrDefault().MinValue = 0;
		ratings.LastOrDefault().MaxValue = 100;
		if (isMinCheck && count != 0 && count < totalCount)
		{
			if (count < totalCount - 1 && intValue < ratings[count - 1].MaxValue)
			{
				intValue = ratings[count - 1].MaxValue;
			}
			else if (count == totalCount - 1 && isMinCheck && intValue > 99)
			{
				rating.MinValue = 99;
			}
			ratings[count].MinValue = intValue;
		}
		return intValue;
	}

	private void Calculate()
	{
		sectionResults = new List<SectionResultModel>();

		foreach (var section in analysisModel.Sections.OrderBy(x => x.SectionType))
		{
			var groupedQuestions = section.Questions.GroupBy(x => x.QuestionType);
			foreach (var groupedQuestion in groupedQuestions)
			{
				var value = groupedQuestion.Sum(x => x.Value);
				var maxValue = groupedQuestion.Sum(x => x.MaxValue);
				sectionResults.Add(new SectionResultModel()
				{
					Name = GetQuestionName(groupedQuestion.Key),
					Value = value,
					MaxValue = maxValue,
					QuestionType = groupedQuestion.Key,
					Result = (decimal)value / maxValue,
					SectionType = section.SectionType
				});
			}
		}
	}
	private ResultType GetResultType(SectionType sectionType)
	{
		switch (sectionType)
		{
			case SectionType.InternalVulnerabilityCriteria:
				return ResultType.InternalVulnerabilityResult;
			case SectionType.ExternalSecurityCriteria:
				return ResultType.ExternalSecurityResult;
			case SectionType.ExternalVulnerabilityCriteria:
				return ResultType.ExternalVulnerabilityResult;
			case SectionType.InternalSecurityCriteria:
				return ResultType.InternalSecurityResult;
			case SectionType.RegimeSecurityAspects:
				return ResultType.OrganizationalRegimeResult;
			case SectionType.OrganizationalSecurityAspects:
				return ResultType.OrganizationalRegimeResult;
			default:
				return ResultType.InternalVulnerabilityResult;
		}
	}

	async Task DownloadText()
	{
		var analysisModelDTO = new AnalysisModelDTO();

		analysisModelDTO.CalculatedResults = calculatedResults;
		analysisModelDTO.RatingTables = ratingTables;
		analysisModelDTO.Results = results;
		analysisModelDTO.SectionResults = sectionResults;
		analysisModelDTO.AnalysisModel = analysisModel;

		string jsonString = JsonSerializer.Serialize(analysisModelDTO);
		await JSRuntime.InvokeAsync<object>("DownloadFile", "analysis.txt", jsonString);
	}

	async Task UploadFile(IFileListEntry[] files)
	{
		var file = files.FirstOrDefault();
		showErrorText = false;
		errorText = string.Empty;
		showResult = false;
		showTables = false;
		showQuestions = true;
		if (file != null)
		{
			using (var reader = new System.IO.StreamReader(file.Data))
			{
				var content = await reader.ReadToEndAsync();
				try
				{
					var model = JsonSerializer.Deserialize<AnalysisModelDTO>(content);
					analysisModel = model.AnalysisModel;
					calculatedResults = model.CalculatedResults;
					ratingTables = model.RatingTables;
					results = model.Results;
					sectionResults = model.SectionResults;
				}
				catch (Exception)
				{
					return;
				}
			}
		}
	}

#line default
#line hidden
#nullable disable
        [global::Microsoft.AspNetCore.Components.InjectAttribute] private IJSRuntime JSRuntime { get; set; }
        [global::Microsoft.AspNetCore.Components.InjectAttribute] private HttpClient Http { get; set; }
    }
}
#pragma warning restore 1591
