namespace SqlDynamite.Common

open System
open StackExchange.Redis

type RedisConnection() =
    inherit NoSqlConnection()

    override this.Open () =
        let parts = this._connectionString.Split(';')
        let cs = parts.[0].Split(':')
        let db = if String.IsNullOrWhiteSpace(parts.[1]) then 0 else Int32.Parse(parts.[1].Replace("db", ""))
        let port = if cs.Length = 2 then Int32.Parse(cs.[1]) else 6379
        let password = if parts.Length = 3 then parts.[2].Replace("Password=", "") else ""
        let co = new ConfigurationOptions()
        co.EndPoints.Add(cs.[0], port)
        co.DefaultDatabase <- db
        if not (String.IsNullOrWhiteSpace(password)) then co.Password <- password
        let cm = ConnectionMultiplexer.Connect(co)
        ignore(cm.GetDatabase().Ping())
        this.ChangeDatabase(sprintf "%d" db)
        ()

    override this.ServerVersion with get() =
                                     let parts = this._connectionString.Split(';')
                                     let cs = parts.[0].Split(':')
                                     let _ = if String.IsNullOrWhiteSpace(parts.[1]) then 0 else Int32.Parse(parts.[1].Replace("db", ""))
                                     let port = if cs.Length = 2 then Int32.Parse(cs.[1]) else 6379
                                     let password = if parts.Length = 3 then parts.[2].Replace("Password=", "") else ""
                                     let co = new ConfigurationOptions()
                                     co.EndPoints.Add(cs.[0], port)
                                     if not (String.IsNullOrWhiteSpace(password)) then co.Password <- password
                                     let cm = ConnectionMultiplexer.Connect(co)
                                     cm.GetServer(cs.[0], port).Version.ToString()
