/*
Данный файл является частью кампании "campaign_II_ZG26".
Автор: Вихарев Евгений aka Geniok.
Дата: 06.01.2012
*/


//$reference Campaign.dll
//-$debug

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using maddox.game;
using maddox.game.world;
using maddox.GP;

public class BriefingParser
{
    private struct SectionPair
    {
        public String Section;
        public String Title;
        public String Key;
    }

    private Dictionary<SectionPair, string> keyPairs = new Dictionary<SectionPair, string>();
    private String briefingFilePath;

    public BriefingParser(String briefingPath)
    {
        TextReader briefingFile = null;
        String strLine = null;
        String currentRoot = null;
        String currentTitle = null;
        String[] keyPair = null;

        briefingFilePath = briefingPath;

        try
        {
            briefingFile = new StreamReader(briefingPath);

            strLine = briefingFile.ReadLine();

            while (strLine != null)
            {
                if (strLine != "")
                {
                    if (strLine.StartsWith("[") && strLine.EndsWith("]"))
                    {
                        currentRoot = strLine.Substring(1, strLine.Length - 2);
                    }
                    else if (strLine.StartsWith("<") && strLine.EndsWith(">"))
                    {
                        currentTitle = strLine.Substring(1, strLine.Length - 2);
                    }
                    else
                    {
                        keyPair = strLine.Split(new char[] { '=' }, 2);

                        SectionPair sectionPair;
                        String value = null;

                        if (currentRoot == null)
                        {
                            currentRoot = "[1]";
                        }
                        if (currentTitle == null)
                        {
                            currentTitle = "<Name>";
                        }

                        sectionPair.Section = currentRoot;
                        sectionPair.Title = currentTitle;
                        sectionPair.Key = keyPair[0];

                        if (keyPair.Length > 1)
                        {
                            value = keyPair[1];
                        }

                        keyPairs.Add(sectionPair, value);
                    }
                }
                strLine = briefingFile.ReadLine();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (briefingFile != null)
            {
                briefingFile.Close();
            }
        }
    }

    public void AddSetting(String sectionName, String titleName, String settingName, String settingValue)
    {
        SectionPair sectionPair;
        sectionPair.Section = sectionName;
        sectionPair.Title = titleName;
        sectionPair.Key = settingName;

        if (keyPairs.ContainsKey(sectionPair))
        {
            keyPairs.Remove(sectionPair);
        }

        keyPairs.Add(sectionPair, settingValue);

        SaveSettings();
    }

    public void AddSetting(String sectionName, String titleName, String settingName)
    {
        AddSetting(sectionName, titleName, settingName, null);
    }

    private void SaveSettings()
    {
        ArrayList sections = new ArrayList();
        ArrayList titles = new ArrayList();
        String tmpValue = "";
        String strToSave = "";

        foreach (SectionPair sectionPair in keyPairs.Keys)
        {
            if (!sections.Contains(sectionPair.Section))
            {
                sections.Add(sectionPair.Section);
            }
            if (!titles.Contains(sectionPair.Title))
            {
                titles.Add(sectionPair.Title);
            }
        }

        foreach (String section in sections)
        {
            strToSave += ("[" + section + "]\r\n");

            foreach (String title in titles)
            {
                strToSave += ("<" + title + ">\r\n");

                foreach (SectionPair sectionPair in keyPairs.Keys)
                {
                    if (sectionPair.Section == section)
                    {
                        if (sectionPair.Title == title)
                        {
                            tmpValue = (String)keyPairs[sectionPair];

                            strToSave += (sectionPair.Key + tmpValue + "\r\n");
                        }
                    }
                }
            }
            strToSave += "\r\n";
        }

        try
        {
            TextWriter tw = new StreamWriter(briefingFilePath);
            tw.Write(strToSave);
            tw.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

public class Mission : maddox.game.campaign.Mission
{
    AiActor a1 = null;
    AiAircraft airc1 = null;
    int countPlayerWins = 0;
    int countDead = 0;
    bool isComplete = false;
    int score = 0;

    private static string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    private static string FILE_NAME = mydocpath + @"\1C SoftClub\il-2 sturmovik cliffs of dover\mission\campaign\campaign_II_ZG26\Score.data";

    private static void writeScore(int scr)
    {
        using (FileStream fs = new FileStream(FILE_NAME, FileMode.Create))
        {
            using (BinaryWriter w = new BinaryWriter(fs))
            {
                w.Write(scr);
            }
        }
    }

    private static int readScore()
    {
        using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
        {
            using (BinaryReader r = new BinaryReader(fs))
            {
                return (r.ReadInt32());
            }
        }
    }

    private void serverMessage(string msg)
    {
        Player pl = GamePlay.gpPlayer();
        Player[] players = { pl };
        object[] args = { msg };
        GamePlay.gpLogServer(players, msg, args);
    }

    private void HUDMessgeTo(string message)
    {
        Player pl = GamePlay.gpPlayer();
        String namePlayer = pl.Name();
        GamePlay.gpHUDLogCenter(namePlayer + ": " + message);
    }

    public override void OnBattleStarted()
    {
        base.OnBattleStarted();
    }

    private void checkLanded(AiAircraft aircraft)
    {
        if (GamePlay.gpPlayer().Place() == aircraft)
        {
            Campaign.battleSuccess = true;

            isComplete = true;
            score += 100;

            HUDMessgeTo("Герр Лейтенант Вы выполнили поставленную перед вами задачу!");
            Timeout(10.0, () =>
            {
                GamePlay.gpHUDLogCenter("Для выхода из миссии нажмите ESC!");
            });
        }
    }

    public override void OnAircraftLanded(int missionNumber, string shortName, AiAircraft aircraft)
    {
        checkLanded(aircraft);
    }

    public override void OnAircraftCrashLanded(int missionNumber, string shortName, AiAircraft aircraft)
    {
        checkLanded(aircraft);
    }

    public override void OnBattleStoped()
    {
        base.OnBattleStoped();

        if (isComplete)
        {
            writeScore(score);

            BriefingParser parser = new BriefingParser(@"..\il-2 sturmovik cliffs of dover\parts\bob\mission\campaign\campaign_II_ZG26\DE_02.BRIEFING");
            parser.AddSetting("2", "Description", "Ваши очки:", readScore().ToString());
        }
    }
}