using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using LitJson;

public partial class Plugins_getAreas : System.Web.UI.Page
{
    protected DataTable _areas;
    public DataTable Areas
    {
        get
        {
            if (_areas == null)
            {
                string cacheName = "Areas";
                _areas = (DataTable)HttpRuntime.Cache.Get(cacheName);
                if (_areas == null)
                {
                    _areas = new DataTable();
                    string dbpath = AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "\\Areas.db";
                    if (System.IO.File.Exists(dbpath))
                    {
                        eDataBase db = new eDataBase("Data Source=|DataDirectory|\\Areas.db;Version=3;Synchronous=off;", "System.Data.SQLite");
                        _areas = db.getDataTable("select * from Areas");
                        if(_areas.Rows.Count>0) HttpRuntime.Cache.Insert(cacheName, _areas);
                    }                   
                }
            }
            return _areas;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string key = eParameters.QueryString("key");
        DataRow[] rows = new DataTable().Select();
        JsonData json = JsonMapper.ToObject("[]");
        if (eUser.Areas.Count > 0 && key.Length > 0 && Areas.Columns.Contains("name"))
        {
            rows = Areas.Select("name like '" + key + "%' or  NamePY like '" + key + "%'");
            foreach (DataRow dr in rows)
            {
                JsonData item = new JsonData();
                string name = dr["name"].ToString();
                //item["name"] = name;
                string addr = dr["Province"].ToString() + dr["City"].ToString();
                if (Convert.ToInt32(dr["levelType"]) > 3)
                {
                    DataRow[] rs = Areas.Select("ID=" + dr["ParentId"].ToString());
                    if (rs.Length > 0)
                    {
                        addr += rs[0]["name"].ToString();
                    }
                }
                else
                {
                    addr += dr["District"].ToString();
                }
                if (!addr.Contains(name)) addr += name;
                item["addr"] = addr;
                item["lng"] = Convert.ToDouble(dr["Lng"]);
                item["lat"] = Convert.ToDouble(dr["Lat"]);
                json.Add(item);
            }
            //eBase.Writeln(rows.Length.ToString());
        }
        eBase.WriteJson(json.ToJson());
    }
}