summaryrefslogtreecommitdiff
path: root/Aktywator/Bws.cs
blob: 7f8a899789da9157e6759495aef2c14f4d15ccc7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Aktywator
{
    class Bws
    {
        private string _filename;
        public string filename
        {
            get { return _filename; }
        }

        public Sql sql;
        public List<Setting> settings;
        private MainForm main;
        public bool settingsChanged = false;

        public Bws(string filename, MainForm main)
        {
            this._filename = filename;
            sql = new Sql(filename);
            this.main = main;
            string[] sections = this.getSections().Split(',');
            main.lWczytywane.Text = this.getBoardRangeText(sections);
            foreach (string section in sections)
            {
                main.cblSections.Items.Add(this.sectorNumberToLetter(Int16.Parse(section)));
            }
            for (int i = 0; i < main.cblSections.Items.Count; i++)
            {
                main.cblSections.SetItemChecked(i, true);
            }
        }

        private int sectorLetterToNumber(string sector)
        {
            return sector[0] - 'A' + 1;
        }

        private string sectorNumberToLetter(int sector)
        {
            char character = (char)('A' - 1 + sector);
            return character.ToString();
        }

        public string getBoardRangeText(string[] sectors)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Wczytywane rozkłady:");
            foreach (string sector in sectors)
            {
                sb.Append("\n      ");
                sb.Append(this.lowBoard(sector));
                sb.Append("-");
                sb.Append(this.highBoard(sector));
                sb.Append(" (sektor ");
                sb.Append(this.sectorNumberToLetter(Int16.Parse(sector)));
                sb.Append(")");
            }
            return sb.ToString();
        }

        public string[] getSelectedSections()
        {
            List<string> sections = new List<string>();
            foreach (string section in main.cblSections.CheckedItems)
            {
                sections.Add(this.sectorLetterToNumber(section).ToString());
            }
            return sections.ToArray();
        }

        public void initSettings()
        {
            settings = new List<Setting>();
            settings.Add(new Setting("ShowResults", main.xShowResults, this));
            settings.Add(new Setting("RepeatResults", main.xRepeatResults, this));
            settings.Add(new Setting("ShowPercentage", main.xShowPercentage, this));
            //settings.Add(new Setting("GroupSections", main.xGroupSections, this));
            settings.Add(new Setting("ShowPairNumbers", main.xShowPairNumbers, this));
            settings.Add(new Setting("IntermediateResults", main.xIntermediateResults, this));
            settings.Add(new Setting("ShowContract", main.xShowContract, this));
            settings.Add(new Setting("LeadCard", main.xLeadCard, this));
            settings.Add(new Setting("MemberNumbers", main.xMemberNumbers, this));
            settings.Add(new Setting("MemberNumbersNoBlankEntry", main.xMemberNumbersNoBlankEntry, this));
            settings.Add(new Setting("BoardOrderVerification", main.xBoardOrderVerification, this));
            settings.Add(new Setting("AutoShutDownBPC", main.xAutoShutDownBPC, this));
            settings.Add(new Setting("BM2ConfirmNP", main.xConfirmNP, this));
            settings.Add(new Setting("BM2RemainingBoards", main.xRemainingBoards, this));
            settings.Add(new Setting("BM2NextSeatings", main.xNextSeatings, this));
            settings.Add(new Setting("BM2ScoreRecap", main.xScoreRecap, this));
            settings.Add(new Setting("BM2AutoShowScoreRecap", main.xAutoShowScoreRecap, this));
            settings.Add(new Setting("BM2ScoreCorrection", main.xScoreCorrection, this));
            settings.Add(new Setting("BM2AutoBoardNumber", main.xAutoBoardNumber, this));
            settings.Add(new Setting("BM2ResetFunctionKey", main.xResetFunctionKey, this));
            settings.Add(new Setting("BM2ViewHandrecord", main.xViewHandrecord, this));
            settings.Add(new Setting("BM2RecordBidding", main.xCollectBidding, this));
            settings.Add(new Setting("BM2RecordPlay", main.xCollectPlay, this));
            settings.Add(new Setting("BM2ValidateLeadCard", main.xCheckLeadCard, this));
        }

        private string getSectionList(string table)
        {
            try
            {
                string s;
                OleDbDataReader d = sql.select("SELECT DISTINCT `Section` FROM " + table + " ORDER BY 1");
                d.Read();
                s = d[0].ToString();
                while (d.Read())
                {
                    s += "," + d[0].ToString();
                }
                return s;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public string getSections()
        {
            return this.getSectionList("RoundData");
        }


        public string sectionsForHandRecords()
        {
            return this.getSectionList("HandRecord");
        }

        public void runBCS()
        {
            string app = Common.ProgramFilesx86() + "\\Bridgemate Pro\\BMPro.exe";
            string param = "";
            param += " /f[" + filename + " ]";
            param += " /s";
            param += " /r";
            //param += " /m";
            param += " /t2";

            string sections = sectionsForHandRecords();
            if (sections != null)
                param += " /h:[" + sections + "]"; // upload rozkladow
            System.Diagnostics.Process.Start(app, param);
        }

        public bool isBm2()
        {
            if (!sql.checkFieldExists("Settings", "BM2PINcode"))
                return false;
            if (!sql.checkFieldExists("PlayerNames", "Name"))
                return false;
            if (!sql.checkFieldExists("PlayerNumbers", "Name"))
                return false;
            if (!sql.checkFieldExists("Settings", "BM2ViewHandrecord"))
                return false;
            if (!sql.checkTableExists("HandRecord"))
                return false;
            if (!sql.checkTableExists("HandEvaluation"))
                return false;

            return true;
        }

        public void convert()
        {
            List<Setting> settings = new List<Setting>();
            settings.Add(new Setting("BM2PINcode", "text(4)", "'5431'"));
            settings.Add(new Setting("BM2ConfirmNP", "bit", "true"));
            settings.Add(new Setting("BM2RemainingBoards", "bit", "false"));
            settings.Add(new Setting("BM2NextSeatings", "bit", "true"));
            settings.Add(new Setting("BM2ScoreRecap", "bit", "false"));
            settings.Add(new Setting("BM2AutoShowScoreRecap", "bit", "false"));
            settings.Add(new Setting("BM2ScoreCorrection", "bit", "false"));
            settings.Add(new Setting("BM2AutoBoardNumber", "bit", "false"));
            settings.Add(new Setting("BM2ResultsOverview", "integer", "1"));
            settings.Add(new Setting("BM2ShowPlayerNames", "integer", "0"));
            settings.Add(new Setting("BM2Ranking", "integer", "0"));
            settings.Add(new Setting("BM2GameSummary", "bit", "false"));
            settings.Add(new Setting("BM2SummaryPoints", "integer", "0"));
            settings.Add(new Setting("BM2PairNumberEntry", "integer", "0"));
            settings.Add(new Setting("BM2ResetFunctionKey", "bit", "false"));
            settings.Add(new Setting("BM2ShowHands", "bit", "false"));
            settings.Add(new Setting("BM2NumberValidation", "integer", "0"));
            settings.Add(new Setting("BM2NameSource", "integer", "2"));
            settings.Add(new Setting("BM2ViewHandrecord", "bit", "false"));
            settings.Add(new Setting("BM2EnterHandrecord", "bit", "false"));
            settings.Add(new Setting("BM2RecordBidding", "bit", "false"));
            settings.Add(new Setting("BM2RecordPlay", "bit", "false"));
            settings.Add(new Setting("BM2ValidateLeadCard", "bit", "false"));

            settings.Add(new Setting("Name", "text(18)", "''", "PlayerNumbers"));
            settings.Add(new Setting("Updated", "bit", "false", "PlayerNumbers"));

            foreach (Setting s in settings)
            {
                try
                {
                    sql.query(s.getAddColumnSql());
                    sql.query(s.getSetDefaultSql());
                }
                catch (OleDbException)
                {
                }
            }

            try
            {
                sql.query("CREATE TABLE PlayerNames (ID integer, Name text(18));");
            }
            catch (OleDbException)
            {
            }

            try
            {
                sql.query("CREATE TABLE HandRecord (`Section` integer, `Board` integer, "
                    + "NorthSpades text(13),NorthHearts text(13),NorthDiamonds text(13),NorthClubs text(13),"
                    + "EastSpades text(13),EastHearts text(13),EastDiamonds text(13),EastClubs text(13),"
                    + "SouthSpades text(13),SouthHearts text(13),SouthDiamonds text(13),SouthClubs text(13),"
                    + "WestSpades text(13),WestHearts text(13),WestDiamonds text(13),WestClubs text(13)"
                    + ");");
            }
            catch (OleDbException)
            {
            }
            try
            {
                sql.query("CREATE TABLE HandEvaluation (`Section` integer, `Board` integer, "
                    + "NorthSpades integer,NorthHearts integer,NorthDiamonds integer,NorthClubs integer,NorthNotrump integer,"
                    + "EastSpades integer,EastHearts integer,EastDiamonds integer,EastClubs integer,EastNotrump integer,"
                    + "SouthSpades integer,SouthHearts integer,SouthDiamonds integer,SouthClubs integer,SouthNotrump integer,"
                    + "WestSpades integer,WestHearts integer,WestDiamonds integer,WestClubs integer,WestNotrump integer,"
                    + "NorthHcp integer,EastHcp integer,SouthHcp integer,WestHcp integer"
                    + ");");
            }
            catch (OleDbException)
            {
            }
            try
            {
                sql.query("CREATE TABLE PlayData ("
                    + "`ID` autoincrement, `Section` integer, `Table` integer, `Round` integer, `Board` integer,"
                    + "`Counter` integer, `Direction` text(2), `Card` text(10), `DateLog` datetime,"
                    + "`TimeLog` datetime, `Erased` bit"
                    + ");");
            }
            catch (OleDbException)
            {
            }
            try
            {
                sql.query("CREATE TABLE BiddingData ("
                    + "`ID` autoincrement, `Section` integer, `Table` integer, `Round` integer, `Board` integer,"
                    + "`Counter` integer, `Direction` text(2), `Bid` text(10), `DateLog` datetime,"
                    + "`TimeLog` datetime, `Erased` bit"
                    + ");");
            }
            catch (OleDbException)
            {
            }
        }

        public void updateSettings()
        {
            sql.query("UPDATE Tables SET UpdateFromRound=997;");
        }

        public void loadSettings()
        {
            StringBuilder errors = new StringBuilder();
            foreach (Setting s in settings)
            {
                try
                {
                    s.load();
                }
                catch (OleDbException)
                {
                    if (errors.Length > 0) errors.Append(", ");
                    errors.Append(s.name);
                }
            }
            main.xShowContract.Checked = (Setting.load("ShowContract", this, errors) == "0");
            main.xShowPlayerNames.Checked = (Setting.load("BM2ShowPlayerNames", this, errors) != "0");
            main.xPINcode.Text = Setting.load("BM2PINcode", this, errors);
            int resultsOverview = 0;
            int.TryParse(Setting.load("BM2ResultsOverview", this, errors), out resultsOverview);
            main.xResultsOverview.SelectedIndex = resultsOverview;

            if (errors.Length > 0)
            {
                MessageBox.Show("Nie można uzyskać dostępu do pól: \n" + errors.ToString() + ".\nPrawdopodobnie te pola nie istnieją.",
                    "Brakuje pól w tabeli Settings", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public void saveSettings()
        {
            StringBuilder errors = new StringBuilder();
            foreach (Setting s in settings)
            {
                try
                {
                    s.save();
                }
                catch (OleDbException)
                {
                    if (errors.Length > 0) errors.Append(", ");
                    errors.Append(s.name);
                }
            }
            Setting.save("ShowContract", main.xShowContract.Checked ? "0" : "1", this, errors);
            Setting.save("BM2ShowPlayerNames", main.xShowPlayerNames.Checked ? "1" : "0", this, errors);
            Setting.save("BM2NameSource", "2", this, errors);
            Setting.save("BM2PINcode", "'" + main.xPINcode.Text + "'", this, errors);
            Setting.save("BM2ResultsOverview", main.xResultsOverview.SelectedIndex.ToString(), this, errors);

            this.loadSettings();
        }

        private int updateName(string section, string table, string direction, string name)
        {
            name = Common.bezOgonkow(name);
            if (name.Length > 18)
                name = name.Substring(0, 18);
            string actual = sql.selectOne("SELECT Name FROM PlayerNumbers WHERE `Section`=" + section + " AND `Table`=" + table
                + " AND `Direction`='" + direction + "'");
            if (actual != name)
            {
                sql.query("UPDATE PlayerNumbers SET Name='" + name + "', Updated=TRUE WHERE `Section`=" + section + " AND `Table`=" + table
                + " AND `Direction`='" + direction + "'");
                return 1;
            }
            else return 0;
        }

        private int getBWSNumber(OleDbDataReader reader, int index)
        {
            switch (Type.GetTypeCode(reader.GetFieldType(index)))
            {
                case TypeCode.Int16:
                    return reader.GetInt16(index);
                case TypeCode.Int32:
                    return reader.GetInt32(index);
            }
            throw new InvalidCastException("Unable to read numeric value from BWS field");
        }

        public void syncNames(Tournament tournament, bool interactive, string startRounds)
        {
            int count = 0, countNew = 0, SKOK_STOLOW = 100;
            OleDbDataReader d;
            startRounds = startRounds.Trim();

            if (tournament.type != Tournament.TYPE_TEAMY)
            {
                if (tournament.type == Tournament.TYPE_PARY && startRounds.Length > 0)
                {
                    d = sql.select("SELECT `Section`, `Table`, NSPair, EWPair FROM RoundData WHERE NSPair>0 AND `Round` in (" + startRounds + ")");
                }
                else
                {
                    string fromRound = sql.selectOne("SELECT min(`Round`) FROM RoundData WHERE NSPair>0");
                    d = sql.select("SELECT `Section`, `Table`, NSPair, EWPair FROM RoundData WHERE `Round`=" + fromRound);
                }
            }
            else
            {
                d = sql.select("SELECT `Section`, `Table`, NSPair, EWPair FROM RoundData WHERE `Table`<=" + SKOK_STOLOW);
            }

            try
            {
                Dictionary<int, List<String>> names = tournament.getNameList();

                while (d.Read())
                {
                    string section = this.getBWSNumber(d, 0).ToString();
                    string table = this.getBWSNumber(d, 1).ToString();
                    int ns = this.getBWSNumber(d, 2);
                    int ew = this.getBWSNumber(d, 3);

                    try
                    {
                        if (!names.ContainsKey(ns))
                        {
                            throw new KeyNotFoundException(ns.ToString());
                        }
                        countNew += updateName(section, table, "N", names[ns][0]);
                        countNew += updateName(section, table, "S", names[ns][1]);
                        count += 2;
                        if (tournament.type == Tournament.TYPE_TEAMY)
                        {
                            countNew += updateName(section, (int.Parse(table) + SKOK_STOLOW).ToString(), "E", names[ns][0]);
                            countNew += updateName(section, (int.Parse(table) + SKOK_STOLOW).ToString(), "W", names[ns][1]);
                            count += 2;
                        }
                    }
                    catch (KeyNotFoundException keyE)
                    {
                        if (interactive)
                        {
                            DialogResult dr = MessageBox.Show("W bws-ie jest para/team (" + keyE.Message + ")"
                            + ", który nie istnieje w wybranym turnieju."
                            + "Może to nie ten turniej?" + "\n\n" + "Kontynuować wczytywanie?",
                            "Zły turniej", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (dr == DialogResult.No) break;
                        }
                    }
                    try
                    {
                        if (!names.ContainsKey(ew))
                        {
                            throw new KeyNotFoundException(ew.ToString());
                        }
                        countNew += updateName(section, table, "E", names[ew][0]);
                        countNew += updateName(section, table, "W", names[ew][1]);
                        count += 2;
                        if (tournament.type == Tournament.TYPE_TEAMY)
                        {
                            countNew += updateName(section, (int.Parse(table) + SKOK_STOLOW).ToString(), "N", names[ew][0]);
                            countNew += updateName(section, (int.Parse(table) + SKOK_STOLOW).ToString(), "S", names[ew][1]);
                            count += 2;
                        }
                    }
                    catch (KeyNotFoundException keyE)
                    {
                        if (interactive)
                        {
                            DialogResult dr = MessageBox.Show("W bws-ie jest para/team (" + keyE.Message + ")"
                            + ", który nie istnieje w wybranym turnieju."
                            + "Może to nie ten turniej?" + "\n\n" + "Kontynuować wczytywanie?",
                            "Zły turniej", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (dr == DialogResult.No) break;
                        }
                    }
                }
                if (interactive)
                {
                    MessageBox.Show("Synchronizacja zakończona!\nPrzejrzanych nazwisk: " + count + "\nZmienionych: " + countNew,
                        "Synchronizacja nazwisk", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (sql.selectOne("SELECT BM2ShowPlayerNames FROM Settings") != "1")
                        MessageBox.Show("Pamiętaj żeby włączyć opcję \"pokazuj nazwiska\"!", "Brakujące ustawienie",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ee)
            {
                if (interactive)
                {
                    MessageBox.Show(ee.Message, "Błąd wczytywania nazwisk", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private int getBoard(string function, string sector)
        {
            sector = sector.Trim();
            StringBuilder query = new StringBuilder();
            query.Append("SELECT ");
            query.Append(function);
            query.Append(" FROM RoundData WHERE lowBoard > 0");
            if (sector.Length > 0)
            {
                query.Append(" AND `Section` IN(");
                query.Append(sector);
                query.Append(")");
            }
            string s = sql.selectOne(query.ToString());
            int i;
            if (int.TryParse(s, out i)) return i;
            else return 0;
        }

        public int lowBoard(string sector = "")
        {
            return this.getBoard("MIN(lowBoard)", sector);
        }

        public int highBoard(string sector = "")
        {
            return this.getBoard("MAX(highBoard)", sector);
        }

        public int highSection()
        {
            string s = sql.selectOne("SELECT max(`Section`) FROM `Tables`");
            int i;
            if (int.TryParse(s, out i)) return i;
            else return 0;
        }

        public int lowSection()
        {
            string s = sql.selectOne("SELECT min(`Section`) FROM `Tables`");
            int i;
            if (int.TryParse(s, out i)) return i;
            else return 0;
        }

        private void clearRecords(string section)
        {
            sql.query("DELETE FROM HandRecord WHERE `Section` = " + section);
            sql.query("DELETE FROM HandEvaluation WHERE `Section` = " + section);
        }

        public void clearHandRecords()
        {
            string sections = this.sectionsForHandRecords();
            if (sections != null)
            {
                foreach (string section in this.sectionsForHandRecords().Split(','))
                {
                    this.clearRecords(section.Trim());
                }
            }
        }

        public int loadHandRecords(PBN pbn)
        {
            int count = 0;
            foreach (string section in this.getSelectedSections())
            {
                this.clearRecords(section);
                for (int i = this.lowBoard(section.Trim()); i <= this.highBoard(section.Trim()); i++)
                    if (pbn.handRecords[i] != null)
                    {
                        HandRecord b = pbn.handRecords[i];
                        StringBuilder str = new StringBuilder(50);
                        str.Append("INSERT INTO HandRecord VALUES (");
                        str.Append(section); str.Append(",");
                        str.Append(i); str.Append(",'");
                        str.Append(String.Join("','", b.north)); str.Append("','");
                        str.Append(String.Join("','", b.east)); str.Append("','");
                        str.Append(String.Join("','", b.south)); str.Append("','");
                        str.Append(String.Join("','", b.west)); str.Append("')");
                        sql.query(str.ToString());
                        int[,] ddTable = pbn.ddTables[i].GetDDTable();
                        if (ddTable != null)
                        {
                            StringBuilder ddStr = new StringBuilder();
                            ddStr.Append("INSERT INTO HandEvaluation VALUES(");
                            ddStr.Append(section); ddStr.Append(",");
                            ddStr.Append(i); ddStr.Append(",");
                            for (int player = 0; player < 4; player++)
                            {
                                for (int denom = 0; denom < 5; denom++)
                                {
                                    ddStr.Append(ddTable[player, denom]);
                                    ddStr.Append(",");
                                }
                            }
                            for (int j = 0; j < 4; j++)
                            {
                                ddStr.Append(b.hpcs[j]);
                                if (j < 3)
                                {
                                    ddStr.Append(",");
                                }
                            }
                            ddStr.Append(")");
                            sql.query(ddStr.ToString());
                        }
                        count++;
                    }
            }
            return count;
        }
    }
}