using Npgsql;
using NpgsqlTypes;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper5.Data.PostgreSql
{
	public partial class PostgresqlDataStore
	{
		public bool ImportFileKnown(FileInfo fi)
		{
			using (NpgsqlConnection connection = new NpgsqlConnection(connectionStringBuilder.ToString()))
			{
				connection.Open();
				NpgsqlCommand command = connection.CreateCommand();
				command.CommandText = "SELECT dateadded FROM skyscraper5_jobs_files_imported WHERE path = @path";
				command.Parameters.AddWithValue("@path", NpgsqlDbType.Text, fi.ToString());
				NpgsqlDataReader dataReader = command.ExecuteReader();
				bool result = dataReader.Read();
				dataReader.Close();
				command.Dispose();
				connection.Close();
				return result;
			}
		}

		public void ImportMarkFileAsKnown(FileInfo fi, TimeSpan duration, int tstype)
		{
			using (NpgsqlConnection connection = new NpgsqlConnection(connectionStringBuilder.ToString()))
			{
				connection.Open();
				NpgsqlCommand command = connection.CreateCommand();
				command.CommandText = "INSERT INTO skyscraper5_jobs_files_imported (path,duration,tstype) VALUES (@path,@duration,@tstype)";
				command.Parameters.AddWithValue("@path", NpgsqlDbType.Text, fi.ToString());
				command.Parameters.AddWithValue("@duration", NpgsqlDbType.Double, duration.TotalSeconds);
				command.Parameters.AddWithValue("@tstype", NpgsqlDbType.Integer, tstype);
				int executeNonQuery = command.ExecuteNonQuery();
				if (executeNonQuery != 1)
					throw new DataException(String.Format("Expect to insert 1 line, but did {0}", executeNonQuery));
				command.Dispose();
				connection.Close();
			}
		}

		public IReadOnlyList<string> ListImportFileByTag1(int tag1)
		{
			List<string> result = new List<string>();
			using (NpgsqlConnection connection = new NpgsqlConnection(connectionStringBuilder.ToString()))
			{
				connection.Open();
				NpgsqlCommand command = connection.CreateCommand();
				command.CommandText = "SELECT path FROM skyscraper5_jobs_files_imported WHERE tag1 = @tag";
				command.Parameters.AddWithValue("@tag", NpgsqlDbType.Integer, tag1);
				NpgsqlDataReader dataReader = command.ExecuteReader();
				while (dataReader.Read())
				{
					result.Add(dataReader.GetString(0));
				}
				dataReader.Close();
				command.Dispose();
				connection.Close();
			}
			return result;
		}
	}
}
