﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data;
using Mono.Data.Sqlite;
using Assets.Shooting_Range.Scripts.Menu;
using System;

public class HighScore : MonoBehaviour {

    private string connectionString;
    public GameObject scorePrefab;
    private List<HighScoreSub> highScores = new List<HighScoreSub>();

    public Transform scoreParent;

	// Use this for initialization
	void Start () {

        connectionString = "URI=file:" + UnityEngine.Application.dataPath + "/HighScoreDB.sqlite";
        //InsertScore("Peter",16);
        showScores();
    }
	
	// Update is called once per frame
	void Update () {
		
	}

    private void InsertScore(string name, int score)
    {
        using (IDbConnection dbConnection = new SqliteConnection(connectionString))
        {
            dbConnection.Open();

            using (IDbCommand dbCmd = dbConnection.CreateCommand())
            {
                string sqlQuery = String.Format("INSERT INTO HighScores(Name,Score) VALUES(\"{0}\",\"{1}\")", name, score);
                dbCmd.CommandText = sqlQuery;
                dbCmd.ExecuteScalar();
                dbConnection.Close();
            }
        }
    }

    private void getScores() {

        highScores.Clear();

        using (IDbConnection dbConnection = new SqliteConnection(connectionString))
        {
            dbConnection.Open();

            using (IDbCommand dbCmd = dbConnection.CreateCommand())
            {
                string sqlQuery = "SELECT * FROM HighScores";
                dbCmd.CommandText = sqlQuery;

                using (IDataReader reader = dbCmd.ExecuteReader())
                {
                    while (reader.Read()) {
                        highScores.Add(new HighScoreSub(reader.GetString(1),reader.GetInt32(2)));
                    }
                    
                    dbCmd.Connection.Close();
                    reader.Close();
                }
            }
        }
    }

    private void showScores() {
        getScores();

        for (int i = 0; i < highScores.Count; i++)
        {
            GameObject tmpObject = Instantiate(scorePrefab);
            HighScoreSub tmpScore = highScores[i];

            tmpObject.GetComponent<HighScoreScript>().setScore(tmpScore.Score.ToString(), tmpScore.name);

            tmpObject.transform.SetParent(scoreParent);
        }

    }
}
