File: Order.cpp

package info (click to toggle)
freeorion 0.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 194,940 kB
  • sloc: cpp: 186,508; python: 40,969; ansic: 1,164; xml: 719; makefile: 32; sh: 7
file content (2052 lines) | stat: -rw-r--r-- 78,127 bytes parent folder | download
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
#include "Order.h"

#include <fstream>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <boost/uuid/nil_generator.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "AppInterface.h"
#include "i18n.h"
#include "Logger.h"
#include "OrderSet.h"
#include "../Empire/Empire.h"
#include "../Empire/EmpireManager.h"
#include "../universe/Building.h"
#include "../universe/Condition.h"
#include "../universe/Fleet.h"
#include "../universe/Pathfinder.h"
#include "../universe/Planet.h"
#include "../universe/ShipDesign.h"
#include "../universe/Ship.h"
#include "../universe/Species.h"
#include "../universe/System.h"
#include "../universe/Universe.h"
#include "../universe/UniverseObject.h"


/////////////////////////////////////////////////////
// Order
/////////////////////////////////////////////////////
std::shared_ptr<Empire> Order::GetValidatedEmpire(ScriptingContext& context) const {
    auto empire = context.GetEmpire(EmpireID());
    if (!empire)
        throw std::runtime_error("Invalid empire ID specified for order.");
    return empire;
}

void Order::Execute(ScriptingContext& context) const {
    if (m_executed)
        return;
    m_executed = true;

    ExecuteImpl(context);
}

bool Order::Undo(ScriptingContext& context) const {
    auto undone =  UndoImpl(context);
    if (undone)
        m_executed = false;
    return undone;
}

namespace {
#if defined(__cpp_lib_constexpr_string) && ((!defined(__GNUC__) || (__GNUC__ > 12) || (__GNUC__ == 12 && __GNUC_MINOR__ >= 2))) && ((!defined(_MSC_VER) || (_MSC_VER >= 1934))) && ((!defined(__clang_major__) || (__clang_major__ >= 17)))
    constexpr std::string EMPTY_STRING;
#else
    const std::string EMPTY_STRING;
#endif

    const std::string& ExecutedTag(const Order* order) {
        if (order && !order->Executed())
            return UserString("ORDER_UNEXECUTED");
        return EMPTY_STRING;
    }

    // checks for first and continuation bytes in allowed ranges for UTF8
    // doesn't check for overlong sequences
    constexpr bool IsValidUTF8(std::string_view sv) {
        if (sv.empty())
            return true;

        auto it = sv.begin();
        auto dist = std::distance(it, sv.end());

        while (true) {
            const uint8_t c = *it;
            const std::ptrdiff_t sequence_length =
                (c <= 0x7F) ? 1 :
                (c >= 0xC2 && c <= 0xDF) ? 2 :
                (c >= 0xE0 && c <= 0xEF) ? 3 :
                (c >= 0xF0) ? 4 : 0;

            if (dist < sequence_length || sequence_length == 0)
                return false;

            if (sequence_length == 1) {
                dist -= 1;

            } else if (sequence_length == 2) {
                const uint8_t c2 = *++it;
                if (c2 < 0x80 || c2 > 0xBF)
                    return false;
                dist -= 2;

            } else if (sequence_length == 3) {
                const uint8_t c2 = *++it;
                if (c2 < 0x80 || c2 > 0xBF)
                    return false;
                const uint8_t c3 = *++it;
                if (c3 < 0x80 || c3 > 0xBF)
                    return false;
                dist -= 3;

            }  else if (sequence_length == 4) {
                const uint8_t c2 = *++it;
                if (c2 < 0x80 || c2 > 0xBF)
                    return false;
                const uint8_t c3 = *++it;
                if (c3 < 0x80 || c3 > 0xBF)
                    return false;
                const uint8_t c4 = *++it;
                if (c4 < 0x80 || c4 > 0xBF)
                    return false;
                dist -= 4;
            }

            ++it;

            if (dist < 1)
                return true;
        }

        return true;
    };

    template <std::size_t N>
    constexpr bool IsValidUTF8(std::array<char, N> arr)
    { return IsValidUTF8(std::string_view{arr.data(), arr.size()}); }

    static_assert(IsValidUTF8("test string!"));

#if defined(__cpp_lib_char8_t)
    constexpr std::u8string_view long_chars = u8"αbåオーガитیای مجهو ";
    constexpr auto long_chars_arr = []() {
        std::array<std::string_view::value_type, long_chars.size()> retval{};
        for (std::size_t idx = 0; idx < retval.size(); ++idx)
            retval[idx] = long_chars[idx];
        return retval;
    }();
    constexpr std::string_view long_chars_sv(long_chars_arr.data(), long_chars_arr.size());
#else
    constexpr std::string_view long_chars_sv = u8"αbåオーガитیای مجهو";
#endif
    static_assert(IsValidUTF8(long_chars_sv));

    static_assert(IsValidUTF8(""));

    constexpr auto ch = [](const uint8_t u) -> char { return static_cast<char>(u); };

    constexpr std::array<char, 4> some_chars1{33, 53, ch(225), 90}; // two ascii chars, then a truncated sequence
    static_assert(!IsValidUTF8(some_chars1));

    constexpr std::array<char, 1> some_chars2{ch(239)}; // truncated 3 byte sequence
    static_assert(!IsValidUTF8(some_chars2));

    constexpr std::array<char, 4> some_chars3{ch(255), 1, 80, 80}; // 4 byte sequence with second byte that is not a continuation byte
    static_assert(!IsValidUTF8(some_chars3));

    constexpr std::array<char, 4> some_chars4{50, 60, ch(192), 80}; // two ascii chars, then an invalid first byte
    static_assert(!IsValidUTF8(some_chars4));

    constexpr bool IsControlChar(const uint8_t c) noexcept
    { return c < 0x20 || c == 0x7F || (c >= 0x81 && c <= 0x9F); }

    constexpr std::string_view formatting_chars = "<>;:,.@#$%&*(){}'\"/?\\`[]|\a\b\f\n\r\t\b";
    constexpr bool IsFormattingChar(char c)
    { return formatting_chars.find(c) != std::string_view::npos; }
}

////////////////////////////////////////////////
// RenameOrder
////////////////////////////////////////////////
RenameOrder::RenameOrder(int empire, int object, std::string name,
                         const ScriptingContext& context) :
    Order(empire),
    m_object(object),
    m_name(std::move(name))
{
    if (!Check(empire, object, m_name, context))
        m_object = INVALID_OBJECT_ID;
}

std::string RenameOrder::Dump() const
{ return boost::io::str(FlexibleFormat(UserString("ORDER_RENAME")) % m_object % m_name) + ExecutedTag(this); }

bool RenameOrder::Check(int empire, int object, std::string new_name,
                        const ScriptingContext& context)
{
    if (new_name.size() > 64) {
        ErrorLogger() << "RenameOrder::Check() : passed an overly long new_name of size: " << new_name.size();
        return false;
    }

#if defined(FREEORION_ANDROID)
    boost::trim(new_name);
#else
    auto& locale = GetLocale();
    boost::trim(new_name, locale);
#endif

    // disallow nameless objects
    if (new_name.empty()) {
        ErrorLogger() << "RenameOrder::Check() : passed an empty new_name.";
        return false;
    }

    // check UTF8 valididty
    if (!IsValidUTF8(new_name)) {
        ErrorLogger() << "RenameOrder::Check() : passed invalid UTF8 new_name.";
        return false;
    }

    // disallow control characters
    if (std::any_of(new_name.begin(), new_name.end(), IsControlChar)) {
        ErrorLogger() << "RenameOrder::Check : passed control character in name.";
        return false;
    }

    // disallow formatting characters
    if (std::any_of(new_name.begin(), new_name.end(), IsFormattingChar)) {
        ErrorLogger() << "RenameOrder::Check : passed formatting character in name.";
        return false;
    }

    auto obj = context.ContextObjects().get(object);

    if (!obj) {
        ErrorLogger() << "RenameOrder::Check() : passed an invalid object.";
        return false;
    }

    // verify that empire specified in order owns specified object
    if (!obj->OwnedBy(empire)) {
        ErrorLogger() << "RenameOrder::Check() : Object " << object << " is"
                      << " not owned by empire " << empire << ".";
        return false;
    }

    if (obj->Name() == new_name) {
        ErrorLogger() << "RenameOrder::Check() : Object " << object
                      << " should renamed to the same name.";
        return false;
    }

    return true;
}

void RenameOrder::ExecuteImpl(ScriptingContext& context) const {
    if (!Check(EmpireID(), m_object, m_name, context))
        return;

    GetValidatedEmpire(context);

    auto obj = context.ContextObjects().get(m_object);

    obj->Rename(m_name);
}

////////////////////////////////////////////////
// CreateFleetOrder
////////////////////////////////////////////////
NewFleetOrder::NewFleetOrder(int empire, std::string fleet_name,
                             std::vector<int> ship_ids,
                             const ScriptingContext& context,
                             bool aggressive, bool passive, bool defensive) :
    NewFleetOrder(empire, std::move(fleet_name), std::move(ship_ids),
                  aggressive ? FleetAggression::FLEET_AGGRESSIVE :
                  defensive ? FleetAggression::FLEET_DEFENSIVE :
                  passive ? FleetAggression::FLEET_PASSIVE :
                  FleetAggression::FLEET_OBSTRUCTIVE, 
                  context)
{}

NewFleetOrder::NewFleetOrder(int empire, std::string fleet_name,
                             std::vector<int> ship_ids, FleetAggression aggression,
                             const ScriptingContext& context) :
    Order(empire),
    m_fleet_name(std::move(fleet_name)),
    m_fleet_id(INVALID_OBJECT_ID),
    m_ship_ids(std::move(ship_ids)),
    m_aggression(aggression)
{
    if (!Check(empire, m_fleet_name, m_ship_ids, m_aggression, context))
        return;
}

bool NewFleetOrder::Aggressive() const noexcept
{ return m_aggression == FleetAggression::FLEET_AGGRESSIVE; }

std::string NewFleetOrder::Dump() const {
    const std::string& aggression_text =
        m_aggression == FleetAggression::FLEET_AGGRESSIVE ? UserString("FLEET_AGGRESSIVE") :
        m_aggression == FleetAggression::FLEET_OBSTRUCTIVE ? UserString("FLEET_OBSTRUCTIVE") :
        m_aggression == FleetAggression::FLEET_DEFENSIVE ? UserString("FLEET_DEFENSIVE") :
        m_aggression == FleetAggression::FLEET_PASSIVE ? UserString("FLEET_PASSIVE") :
        UserString("INVALID_FLEET_AGGRESSION");

    return boost::io::str(FlexibleFormat(UserString("ORDER_FLEET_NEW"))
                          % m_fleet_name
                          % std::to_string(m_ship_ids.size())
                          % aggression_text)
        + ExecutedTag(this);
}

bool NewFleetOrder::Check(int empire, const std::string& fleet_name, const std::vector<int>& ship_ids,
                          FleetAggression aggression, const ScriptingContext& context)
{
    if (ship_ids.empty()) {
        ErrorLogger() << "Empire " << empire << " attempted to create a new fleet (" << fleet_name << ") without ships";
        return false;
    }

    if (auto pos = fleet_name.find_first_of(formatting_chars); pos != std::string::npos) {
        ErrorLogger() << "New fleet name contains banned character: \"" << fleet_name[pos] << "\"";
        return false;
    }

    int system_id = INVALID_OBJECT_ID;

    std::set<int> arrival_starlane_ids;
    for (const auto* ship : context.ContextObjects().findRaw<Ship>(ship_ids)) {
        if (!ship) {
            ErrorLogger() << "Empire " << empire << " attempted to create a new fleet (" << fleet_name
                          << ") with an invalid ship";
            return false;
        }

        auto ship_fleet = context.ContextObjects().get<Fleet>(ship->FleetID());
        if (!ship_fleet)
            continue;   // OK
        auto arr_lane = ship_fleet->ArrivalStarlane();
        if (arr_lane == INVALID_OBJECT_ID) // newly produced fleets have invalid object ID as arrival lane for one turn. this lets them be merged with fleets that have had their arrival lane set to their system
            arr_lane = ship_fleet->SystemID();
        arrival_starlane_ids.insert(arr_lane);
    }
    if (arrival_starlane_ids.size() > 1) {
        ErrorLogger() << "Empire " << empire << " attempted to create a new fleet with ships from multiple arrival starlanes";
        return false;
    }


    for (const auto* ship : context.ContextObjects().findRaw<Ship>(ship_ids)) {
        // verify that empire is not trying to take ships from somebody else's fleet
        if (!ship->OwnedBy(empire)) {
            ErrorLogger() << "Empire " << empire << " attempted to create a new fleet (" << fleet_name
                          << ") with ships from another's (" << ship->Owner() << ") fleet.";
            return false;
        }
        if (ship->SystemID() == INVALID_OBJECT_ID) {
            ErrorLogger() << "Empire " << empire << " attempted to create a new fleet (" << fleet_name
                          << ") with ship (" << ship->ID() << ") not in a system";
            return false;
        }

        if (system_id == INVALID_OBJECT_ID)
            system_id = ship->SystemID();

        if (ship->SystemID() != system_id) {
            ErrorLogger() << "Empire " << empire << " attempted to make a new fleet (" << fleet_name
                          << ") from ship (" << ship->ID() << ") in the wrong system (" << ship->SystemID()
                          << " not " << system_id << ")";
            return false;
        }
    }

    if (system_id == INVALID_OBJECT_ID) {
        ErrorLogger() << "Empire " << empire << " attempted to create a new fleet (" << fleet_name
                      << ") outside a system";
        return false;
    }
    auto system = context.ContextObjects().get<System>(system_id);
    if (!system) {
        ErrorLogger() << "Empire " << empire << " attempted to create a new fleet (" << fleet_name
                      << ") in a nonexistant system (" << system_id << ")";
        return false;
    }

    return true;
}

void NewFleetOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_fleet_name, m_ship_ids, m_aggression, context))
        return;

    Universe& u = context.ContextUniverse();
    ObjectMap& o = context.ContextObjects();
    const auto& ids_as_flatset{context.EmpireIDs()};
    const std::vector<int> empire_ids{ids_as_flatset.begin(), ids_as_flatset.end()};

    u.InhibitUniverseObjectSignals(true);

    // validate specified ships
    auto validated_ships = o.findRaw<Ship>(m_ship_ids);

    int system_id = validated_ships[0]->SystemID();
    auto system = o.get<System>(system_id);

    std::shared_ptr<Fleet> fleet;
    if (m_fleet_id == INVALID_OBJECT_ID) {
        // create fleet
        fleet = u.InsertNew<Fleet>(m_fleet_name, system->X(), system->Y(),
                                   EmpireID(), context.current_turn);
        m_fleet_id = fleet->ID();
    } else {
        fleet = u.InsertByEmpireWithID<Fleet>(EmpireID(), m_fleet_id, m_fleet_name,
                                              system->X(), system->Y(), EmpireID(),
                                              context.current_turn);
    }

    if (!fleet) {
        ErrorLogger() << "Unable to create fleet.";
        return;
    }

    fleet->GetMeter(MeterType::METER_STEALTH)->SetCurrent(Meter::LARGE_VALUE);
    fleet->SetAggression(m_aggression);

    // an ID is provided to ensure consistancy between server and client universes
    u.SetEmpireObjectVisibility(EmpireID(), fleet->ID(), Visibility::VIS_FULL_VISIBILITY);

    system->Insert(fleet, System::NO_ORBIT, context.current_turn, o);

    // new fleet will get same m_arrival_starlane as fleet of the first ship in the list.
    auto first_ship{validated_ships[0]};
    auto first_fleet = o.get<Fleet>(first_ship->FleetID());
    if (first_fleet)
        fleet->SetArrivalStarlane(first_fleet->ArrivalStarlane());

    std::vector<Fleet*> modified_fleets;
    int ordered_moved_turn = BEFORE_FIRST_TURN;
    // remove ships from old fleet(s) and add to new
    for (auto* ship : validated_ships) {
        if (auto* old_fleet = o.getRaw<Fleet>(ship->FleetID())) {
            ordered_moved_turn = std::max(ordered_moved_turn, old_fleet->LastTurnMoveOrdered());
            old_fleet->RemoveShips({ship->ID()});
            modified_fleets.push_back(old_fleet);
        }
        ship->SetFleetID(fleet->ID());
    }
    std::sort(modified_fleets.begin(), modified_fleets.end());
    modified_fleets.erase(std::unique(modified_fleets.begin(), modified_fleets.end()), modified_fleets.end());
    fleet->AddShips(m_ship_ids);
    fleet->SetMoveOrderedTurn(ordered_moved_turn);

    if (m_fleet_name.empty())
        fleet->Rename(fleet->GenerateFleetName(context));

    u.InhibitUniverseObjectSignals(false);

    system->FleetsInsertedSignal(std::vector<int>{fleet->ID()}, o);
    system->StateChangedSignal();

    // Signal changed state of modified fleets and remove any empty fleets.
    for (auto* modified_fleet : modified_fleets) {
        if (!modified_fleet->Empty()) {
            modified_fleet->StateChangedSignal();
        } else {
            if (auto modified_fleet_system = o.getRaw<System>(modified_fleet->SystemID()))
                modified_fleet_system->Remove(modified_fleet->ID());

            u.Destroy(modified_fleet->ID(), empire_ids);
        }
    }
}

////////////////////////////////////////////////
// FleetMoveOrder
////////////////////////////////////////////////
FleetMoveOrder::FleetMoveOrder(int empire_id, int fleet_id, int dest_system_id,
                               bool append, const ScriptingContext& context) :
    Order(empire_id),
    m_fleet(fleet_id),
    m_dest_system(dest_system_id),
    m_append(append)
{
    if (!Check(empire_id, fleet_id, dest_system_id, append, context))
        return;

    auto fleet = context.ContextObjects().get<Fleet>(m_fleet);

    int start_system = fleet->SystemID();
    if (start_system == INVALID_OBJECT_ID)
        start_system = fleet->NextSystemID();
    if (append && !fleet->TravelRoute().empty())
        start_system = fleet->TravelRoute().back();

    auto short_path = context.ContextUniverse().GetPathfinder()->ShortestPath(
        start_system, m_dest_system, EmpireID(), context.ContextObjects());
    if (short_path.first.empty()) {
        ErrorLogger() << "FleetMoveOrder generated empty shortest path between system " << start_system
                      << " and " << m_dest_system << " for empire " << EmpireID()
                      << " with fleet " << m_fleet;
        return;
    }

    // if in a system now, don't include it in the route
    if (short_path.first.front() == fleet->SystemID()) {
        DebugLogger() << "FleetMoveOrder removing fleet " << m_fleet
                      << " current system location " << fleet->SystemID()
                      << " from shortest path to system " << m_dest_system;
        short_path.first.erase(short_path.first.begin()); // pop_front();
    }

    m_route = std::move(short_path.first);

    // ensure a zero-length (invalid) route is not requested / sent to a fleet
    if (m_route.empty())
        m_route.push_back(start_system);
}

std::string FleetMoveOrder::Dump() const
{ return boost::io::str(FlexibleFormat(UserString("ORDER_FLEET_MOVE")) % m_fleet % m_dest_system) + ExecutedTag(this); }

bool FleetMoveOrder::Check(int empire_id, int fleet_id, int dest_system_id,
                           bool append, const ScriptingContext& context)
{
    auto fleet = context.ContextObjects().getRaw<Fleet>(fleet_id);
    if (!fleet) {
        ErrorLogger() << "Empire with id " << empire_id << " ordered fleet with id " << fleet_id << " to move, but no such fleet exists";
        return false;
    }

    if (!fleet->OwnedBy(empire_id) ) {
        ErrorLogger() << "Empire with id " << empire_id << " order to move but does not own fleet with id " << fleet_id;
        return false;
    }

    const auto& known_objs{AppEmpireID() == ALL_EMPIRES ?
        context.ContextUniverse().EmpireKnownObjects(empire_id) : context.ContextObjects()};
    auto dest_system = known_objs.getRaw<System>(dest_system_id);
    if (!dest_system) {
        ErrorLogger() << "Empire with id " << empire_id << " ordered fleet to move to system with id " << dest_system_id << " but no such system is known to that empire";
        return false;
    }

    return true;
}

void FleetMoveOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_fleet, m_dest_system, m_append, context))
        return;

    // convert list of ids to list of System
    auto fleet = context.ContextObjects().get<Fleet>(FleetID());
    if (!fleet) {
        ErrorLogger() << "FleetMoveOrder::ExecuteImpl couldn't get fleet with ID: " << m_fleet;
        return;
    }
    using RouteListT = std::remove_const_t<std::remove_reference_t<decltype(fleet->TravelRoute())>>;
    RouteListT fleet_travel_route{m_append ? fleet->TravelRoute() : RouteListT{}};

    if (m_append && !fleet_travel_route.empty()) {
        DebugLogger() << "FleetMoveOrder::ExecuteImpl appending initial" << [&]() {
            std::stringstream ss;
            for (int waypoint : fleet_travel_route)
                ss << " " << waypoint;
            return ss.str();
        }() << "  with" << [&]() {
            std::stringstream ss;
            for (int waypoint : m_route)
                ss << " " << waypoint;
            return ss.str();
        }();
        fleet_travel_route.pop_back(); // remove last item as it should be the first in the appended route
    }

    std::copy(m_route.begin(), m_route.end(), std::back_inserter(fleet_travel_route));
    DebugLogger() << [&fleet, &fleet_travel_route]() {
        std::stringstream ss;
        ss << "FleetMoveOrder::ExecuteImpl Setting route of fleet " << fleet->ID() << " at system " << fleet->SystemID() << " to: ";
        if (fleet_travel_route.empty())
            return std::string("[empty route]");
        for (int waypoint : fleet_travel_route)
            ss << " " << std::to_string(waypoint);
        return ss.str();
    }();

    if (!fleet_travel_route.empty() && fleet_travel_route.front() == fleet->SystemID()) {
        DebugLogger() << "FleetMoveOrder::ExecuteImpl given route that starts with fleet " << fleet->ID()
                      << "'s current system (" << fleet_travel_route.front() << "); removing it";
        fleet_travel_route.erase(fleet_travel_route.begin()); // pop_front();
    }

    // check destination validity: disallow movement that's out of range
    const auto eta = fleet->ETA(fleet->MovePath(fleet_travel_route, false, context));
    if (eta.first == Fleet::ETA_NEVER || eta.first == Fleet::ETA_OUT_OF_RANGE) {
        DebugLogger() << "FleetMoveOrder::ExecuteImpl rejected out of range move order";
        return;
    }

    try {
        fleet->SetRoute(std::move(fleet_travel_route), context.ContextObjects());
        fleet->SetMoveOrderedTurn(context.current_turn);
        // todo: set last turn ordered moved
    } catch (const std::exception& e) {
        ErrorLogger() << "Caught exception setting fleet route while executing fleet move order: " << e.what();
    }
}

////////////////////////////////////////////////
// FleetTransferOrder
////////////////////////////////////////////////
FleetTransferOrder::FleetTransferOrder(int empire, int dest_fleet, std::vector<int> ships,
                                       const ScriptingContext& context) :
    Order(empire),
    m_dest_fleet(dest_fleet),
    m_add_ships(std::move(ships))
{
    if (!Check(empire, m_dest_fleet, m_add_ships, context))
        ErrorLogger() << "FleetTransferOrder constructor found problem...";
}

std::string FleetTransferOrder::Dump() const {
    std::string ships;
    if (!m_add_ships.empty()) {
        ships.reserve(15*m_add_ships.size()); // guesstimate
        for (auto s : m_add_ships)
            ships.append(std::to_string(s)).append(" ");
        ships.resize(ships.length() - 1);
    }
    return boost::io::str(FlexibleFormat(UserString("ORDER_FLEET_TRANSFER")) % ships % m_dest_fleet) + ExecutedTag(this);
}

bool FleetTransferOrder::Check(int empire_id, int dest_fleet_id, const std::vector<int>& ship_ids,
                               const ScriptingContext& context)
{
    const ObjectMap& objects{context.ContextObjects()};

    auto fleet = objects.get<Fleet>(dest_fleet_id);
    if (!fleet) {
        ErrorLogger() << "Empire attempted to move ships to a nonexistant fleet";
        return false;
    }
    // check that destination fleet is owned by empire
    if (!fleet->OwnedBy(empire_id)) {
        ErrorLogger() << "IssueFleetTransferOrder : passed fleet_id "<< dest_fleet_id << " of fleet not owned by player";
        return false;
    }

    if (fleet->SystemID() == INVALID_OBJECT_ID) {
        ErrorLogger() << "IssueFleetTransferOrder : new fleet is not in a system";
        return false;
    }

    bool invalid_ships{false};

    for (const auto& ship : objects.find<Ship>(ship_ids)) {
        if (!ship) {
            ErrorLogger() << "IssueFleetTransferOrder : passed an invalid ship_id";
            invalid_ships = true;
            break;
        }

        if (!ship->OwnedBy(empire_id)) {
            ErrorLogger() << "IssueFleetTransferOrder : passed ship_id of ship not owned by player";
            invalid_ships = true;
            break;
        }

        if (ship->SystemID() == INVALID_OBJECT_ID) {
            ErrorLogger() << "IssueFleetTransferOrder : ship is not in a system";
            invalid_ships = true;
            break;
        }

        if (ship->SystemID() != fleet->SystemID()) {
            ErrorLogger() << "IssueFleetTransferOrder : passed ship is not in the same system as the target fleet";
            invalid_ships = true;
            break;
        }

        if (ship->FleetID() == dest_fleet_id) {
            ErrorLogger() << "IssueFleetTransferOrder : passed ship that is already in the target fleet";
            invalid_ships = true;
            break;
        }

        if (auto original_fleet = context.ContextObjects().get<Fleet>(ship->FleetID())) {
            auto ship_old_fleet_arr_lane = original_fleet->ArrivalStarlane();
            if (ship_old_fleet_arr_lane == INVALID_OBJECT_ID) // deal with quirky case where new fleets have no arrival lane for one turn
                ship_old_fleet_arr_lane = original_fleet->SystemID();
            auto new_fleet_arr_lane = fleet->ArrivalStarlane();
            if (new_fleet_arr_lane == INVALID_OBJECT_ID)      // same quirky case can affect both source and destination fleets
                new_fleet_arr_lane = fleet->SystemID();

            if (ship_old_fleet_arr_lane != new_fleet_arr_lane) {
                ErrorLogger() << "IssueFleetTransferOrder : passed ship " << ship->ID()
                              << " that is in a fleet " << original_fleet->ID()
                              << " that has a different arrival starlane " << ship_old_fleet_arr_lane
                              << " than the destination fleet " << fleet->ID()
                              << " with arrival starlane " << new_fleet_arr_lane;
                invalid_ships = true;
                break;
            }
        }
    }

    return !invalid_ships;
}

void FleetTransferOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_dest_fleet, m_add_ships, context))
        return;

    // look up the destination fleet
    auto target_fleet = context.ContextObjects().get<Fleet>(m_dest_fleet);

    // check that all ships are in the same system
    auto ships = context.ContextObjects().findRaw<Ship>(m_add_ships);

    context.ContextUniverse().InhibitUniverseObjectSignals(true);

    // remove from old fleet(s)
    std::set<Fleet*> modified_fleets;
    for (auto& ship : ships) {
        if (auto source_fleet = context.ContextObjects().getRaw<Fleet>(ship->FleetID())) {
            source_fleet->RemoveShips({ship->ID()});
            modified_fleets.insert(source_fleet);
        }
        ship->SetFleetID(target_fleet->ID());
    }

    // add to new fleet
    std::vector<int> validated_ship_ids;
    validated_ship_ids.reserve(m_add_ships.size());
    for (const auto& ship : ships)
        validated_ship_ids.push_back(ship->ID());

    target_fleet->AddShips(validated_ship_ids);

    context.ContextUniverse().InhibitUniverseObjectSignals(false);

    // signal change to fleet states
    modified_fleets.insert(target_fleet.get());
    const auto& ids_as_flatset{context.EmpireIDs()};
    const std::vector<int> empire_ids{ids_as_flatset.begin(), ids_as_flatset.end()};

    for (auto* modified_fleet : modified_fleets) {
        if (!modified_fleet) {
            continue;
        } else if (!modified_fleet->Empty()) {
            modified_fleet->StateChangedSignal();
        } else {
            if (auto system = context.ContextObjects().getRaw<System>(modified_fleet->SystemID()))
                system->Remove(modified_fleet->ID());

            context.ContextUniverse().Destroy(modified_fleet->ID(), empire_ids);
        }
    }
}

////////////////////////////////////////////////
// AnnexOrder
////////////////////////////////////////////////
AnnexOrder::AnnexOrder(int empire, int planet, const ScriptingContext& context) :
    Order(empire),
    m_planet(planet)
{ Check(empire, m_planet, context); }

std::string AnnexOrder::Dump() const
{ return boost::io::str(FlexibleFormat(UserString("ORDER_ANNEX")) % m_planet) + ExecutedTag(this); }

bool AnnexOrder::Check(int empire_id, int planet_id, const ScriptingContext& context) {
    const ObjectMap& o = context.ContextObjects();

    const auto* planet = o.getRaw<const Planet>(planet_id);
    if (!planet) {
        ErrorLogger() << "AnnexOrder couldn't get planet with id " << planet_id;
        return false;
    }

    if (empire_id == ALL_EMPIRES) {
        ErrorLogger() << "AnnexOrder given non-empire empire id: " << empire_id;
        return false;
    }

    const auto& planet_species_name = planet->SpeciesName();
    if (planet_species_name.empty()) {
        ErrorLogger() << "AnnexOrder given planet without a species: " << planet_id;
        return false;
    }
    const auto* planet_species = context.species.GetSpecies(planet_species_name);
    if (!planet_species) {
        ErrorLogger() << "AnnexOrder given planet with an unknown species: " << planet_species_name;
        return false;
    }
    const auto* annexation_condition = planet_species->AnnexationCondition();
    if (!annexation_condition) {
        ErrorLogger() << "AnnexOrder given planet with species with no annexation condition: " << planet_species_name;
        return false;
    }

    if (!context.source)
        ErrorLogger() << "AnnexOrder given context with no source... Context source should be an object owned by the order issuing empire";

    if (!context.source->OwnedBy(empire_id))
        ErrorLogger() << "AnnexOrder given context with source not owned by passed in empire id";

    if (!annexation_condition->EvalOne(context, planet)) {
        ErrorLogger() << "AnnexOrder given planet that does not meet its species annexation condition: " << planet_species_name;
        return false;
    }

    // TODO: check IP costs, like adopting policies

    return true;
}

void AnnexOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_planet, context))
        return;

    ObjectMap& objects{context.ContextObjects()};
    if (auto* planet = objects.getRaw<Planet>(m_planet))
        planet->SetIsOrderAnnexedByEmpire(EmpireID());
}

bool AnnexOrder::UndoImpl(ScriptingContext& context) const {
    ObjectMap& objects{context.ContextObjects()};

    auto* planet = objects.getRaw<Planet>(m_planet);
    if (!planet) {
        ErrorLogger() << "AnnexOrder::UndoImpl couldn't get planet with id " << m_planet;
        return false;
    }

    planet->ResetBeingAnnxed();

    return true;
}

////////////////////////////////////////////////
// ColonizeOrder
////////////////////////////////////////////////
ColonizeOrder::ColonizeOrder(int empire, int ship, int planet, const ScriptingContext& context) :
    Order(empire),
    m_ship(ship),
    m_planet(planet)
{ Check(empire, m_ship, m_planet, context); }

std::string ColonizeOrder::Dump() const
{ return boost::io::str(FlexibleFormat(UserString("ORDER_COLONIZE")) % m_planet % m_ship) + ExecutedTag(this); }

bool ColonizeOrder::Check(int empire_id, int ship_id, int planet_id, const ScriptingContext& context) {
    const Universe& u = context.ContextUniverse();
    const ObjectMap& o = context.ContextObjects();
    const SpeciesManager& sm = context.species;

    if (empire_id == ALL_EMPIRES) {
        ErrorLogger() << "ColonizeOrder::Check() : empire " << empire_id << " is not an empire";
        return false;
    }

    auto ship = o.get<Ship>(ship_id);
    if (!ship) {
        ErrorLogger() << "ColonizeOrder::Check() : empire " << empire_id
                      << " passed an invalid ship_id: " << ship_id;
        return false;
    }
    auto fleet = o.get<Fleet>(ship->FleetID());
    if (!fleet) {
        ErrorLogger() << "ColonizeOrder::Check() : empire " << empire_id
                      << " passed ship (" << ship_id << ") with an invalid fleet_id: " << ship->FleetID();
        return false;
    }

    if (!fleet->OwnedBy(empire_id)) {
        ErrorLogger() << "ColonizeOrder::Check() : empire does not own fleet of passed ship";
        return 0;
    }
    if (!ship->OwnedBy(empire_id)) {
        ErrorLogger() << "ColonizeOrder::Check() : got ship that isn't owned by the order-issuing empire";
        return false;
    }

    if (!ship->CanColonize(u, sm)) { // verifies that species exists and can colonize and that ship can colonize
        ErrorLogger() << "ColonizeOrder::Check() : got ship that can't colonize";
        return false;
    }

    auto planet = o.get<Planet>(planet_id);
    float colonist_capacity = ship->ColonyCapacity(u);
    if (!planet) {
        ErrorLogger() << "ColonizeOrder::Check() : couldn't get planet with id " << planet_id;
        return false;
    }
    if (planet->GetMeter(MeterType::METER_POPULATION)->Initial() > 0.0f) {
        ErrorLogger() << "ColonizeOrder::Check() : given planet that already has population";
        return false;
    }
    if (!planet->Unowned() && planet->Owner() != empire_id) {
        ErrorLogger() << "ColonizeOrder::Check() : given planet that owned by another empire";
        return false;
    }
    if (planet->OwnedBy(empire_id) && colonist_capacity == 0.0f) {
        ErrorLogger() << "ColonizeOrder::Check() : given planet that is already owned by empire and colony ship with zero capcity";
        return false;
    }
    if (u.GetObjectVisibilityByEmpire(planet_id, empire_id) < Visibility::VIS_PARTIAL_VISIBILITY) {
        ErrorLogger() << "ColonizeOrder::Check() : given planet that empire has insufficient visibility of";
        return false;
    }
    if (colonist_capacity > 0.0f &&
        planet->EnvironmentForSpecies(context.species, ship->SpeciesName()) < PlanetEnvironment::PE_HOSTILE)
    {
        ErrorLogger() << "ColonizeOrder::Check() : nonzero colonist capacity, " << colonist_capacity
                      << ", and planet " << planet->Name() << " of type, " << planet->Type() << ", that ship's species, "
                      << ship->SpeciesName() << ", can't colonize";
        return false;
    }

    int ship_system_id = ship->SystemID();
    if (ship_system_id == INVALID_OBJECT_ID) {
        ErrorLogger() << "ColonizeOrder::Check() : given id of ship not in a system";
        return false;
    }
    int planet_system_id = planet->SystemID();
    if (ship_system_id != planet_system_id) {
        ErrorLogger() << "ColonizeOrder::Check() : given ids of ship and planet not in the same system";
        return false;
    }

    return true;
}

void ColonizeOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_ship, m_planet, context))
        return;

    ObjectMap& objects{context.ContextObjects()};
    auto ship = objects.get<Ship>(m_ship);
    if (!ship)
        return;
    auto planet = objects.get<Planet>(m_planet);
    if (!planet)
        return;

    planet->SetIsAboutToBeColonized(true);
    ship->SetColonizePlanet(m_planet);

    if (auto fleet = objects.get<Fleet>(ship->FleetID()))
        fleet->StateChangedSignal();
}

bool ColonizeOrder::UndoImpl(ScriptingContext& context) const {
    ObjectMap& objects{context.ContextObjects()};

    auto planet = objects.get<Planet>(m_planet);
    if (!planet) {
        ErrorLogger() << "ColonizeOrder::UndoImpl couldn't get planet with id " << m_planet;
        return false;
    }
    if (!planet->IsAboutToBeColonized()) {
        ErrorLogger() << "ColonizeOrder::UndoImpl planet is not about to be colonized...";
        return false;
    }

    auto ship = objects.get<Ship>(m_ship);
    if (!ship) {
        ErrorLogger() << "ColonizeOrder::UndoImpl couldn't get ship with id " << m_ship;
        return false;
    }
    if (ship->OrderedColonizePlanet() != m_planet) {
        ErrorLogger() << "ColonizeOrder::UndoImpl ship is not about to colonize planet";
        return false;
    }

    planet->SetIsAboutToBeColonized(false);
    ship->ClearColonizePlanet();

    if (auto fleet = objects.get<Fleet>(ship->FleetID()))
        fleet->StateChangedSignal();

    return true;
}

////////////////////////////////////////////////
// InvadeOrder
////////////////////////////////////////////////
InvadeOrder::InvadeOrder(int empire, int ship, int planet, const ScriptingContext& context) :
    Order(empire),
    m_ship(ship),
    m_planet(planet)
{ Check(empire, m_ship, m_planet, context); }

std::string InvadeOrder::Dump() const
{ return boost::io::str(FlexibleFormat(UserString("ORDER_INVADE")) % m_planet % m_ship) + ExecutedTag(this); }

bool InvadeOrder::Check(int empire_id, int ship_id, int planet_id, const ScriptingContext& context) {
    const Universe& u = context.ContextUniverse();
    const ObjectMap& o = context.ContextObjects();

    if (empire_id == ALL_EMPIRES) {
        ErrorLogger() << "InvadeOrder::Check() : empire " << empire_id << " is not an empire";
        return false;
    }

    // make sure ship_id is a ship...
    auto ship = o.get<Ship>(ship_id);
    if (!ship) {
        ErrorLogger() << "IssueInvadeOrder: passed an invalid ship_id";
        return false;
    }

    if (!ship->OwnedBy(empire_id)) {
        ErrorLogger() << "IssueInvadeOrder: empire does not own passed ship";
        return false;
    }
    if (!ship->HasTroops(u)) {
        ErrorLogger() << "InvadeOrder got ship that can't invade";
        return false;
    }

    // get fleet of ship
    auto fleet = o.get<Fleet>(ship->FleetID());
    if (!fleet) {
        ErrorLogger() << "IssueInvadeOrder: ship with passed ship_id has invalid fleet_id";
        return false;
    }

    // make sure player owns ship and its fleet
    if (!fleet->OwnedBy(empire_id)) {
        ErrorLogger() << "IssueInvadeOrder: empire does not own fleet of passed ship";
        return false;
    }

    auto planet = o.get<Planet>(planet_id);
    if (!planet) {
        ErrorLogger() << "InvadeOrder couldn't get planet with id " << planet_id;
        return false;
    }

    if (ship->SystemID() != planet->SystemID()) {
        ErrorLogger() << "InvadeOrder given ids of ship and planet not in the same system";
        return false;
    }

    if (u.GetObjectVisibilityByEmpire(planet_id, empire_id) < Visibility::VIS_BASIC_VISIBILITY) {
        ErrorLogger() << "InvadeOrder given planet that empire reportedly has insufficient visibility of";
        return false;
    }

    if (planet->OwnedBy(empire_id)) {
        ErrorLogger() << "InvadeOrder given planet that is already owned by the order-issuing empire";
        return false;
    }

    if (planet->Unowned() && planet->GetMeter(MeterType::METER_POPULATION)->Initial() == 0.0f) {
        ErrorLogger() << "InvadeOrder given unpopulated planet";
        return false;
    }

    if (planet->GetMeter(MeterType::METER_SHIELD)->Initial() > 0.0f) {
        ErrorLogger() << "InvadeOrder given planet with shield > 0";
        return false;
    }

    if (!planet->Unowned() && context.ContextDiploStatus(planet->Owner(), empire_id) !=
                              DiplomaticStatus::DIPLO_WAR)
    {
        ErrorLogger() << "InvadeOrder given planet owned by an empire not at war with order-issuing empire";
        return false;
    }

    return true;
}

void InvadeOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_ship, m_planet, context))
        return;

    ObjectMap& objects{context.ContextObjects()};
    auto ship = objects.get<Ship>(m_ship);
    auto planet = objects.get<Planet>(m_planet);

    // note: multiple ships, from same or different empires, can invade the same planet on the same turn
    DebugLogger() << "InvadeOrder::ExecuteImpl set for ship " << m_ship << " "
                  << ship->Name() << " to invade planet " << m_planet << " " << planet->Name();
    planet->SetIsAboutToBeInvaded(true);
    ship->SetInvadePlanet(m_planet);

    if (auto fleet = objects.get<Fleet>(ship->FleetID()))
        fleet->StateChangedSignal();
}

bool InvadeOrder::UndoImpl(ScriptingContext& context) const {
    ObjectMap& objects{context.ContextObjects()};

    auto planet = objects.get<Planet>(m_planet);
    if (!planet) {
        ErrorLogger() << "InvadeOrder::UndoImpl couldn't get planet with id " << m_planet;
        return false;
    }

    auto ship = objects.get<Ship>(m_ship);
    if (!ship) {
        ErrorLogger() << "InvadeOrder::UndoImpl couldn't get ship with id " << m_ship;
        return false;
    }
    if (ship->OrderedInvadePlanet() != m_planet) {
        ErrorLogger() << "InvadeOrder::UndoImpl ship is not about to invade planet";
        return false;
    }

    planet->SetIsAboutToBeInvaded(false);
    ship->ClearInvadePlanet();

    if (auto fleet = objects.get<Fleet>(ship->FleetID()))
        fleet->StateChangedSignal();

    return true;
}

////////////////////////////////////////////////
// BombardOrder
////////////////////////////////////////////////
BombardOrder::BombardOrder(int empire, int ship, int planet, const ScriptingContext& context) :
    Order(empire),
    m_ship(ship),
    m_planet(planet)
{ Check(empire, m_ship, m_planet, context); }

std::string BombardOrder::Dump() const
{ return boost::io::str(FlexibleFormat(UserString("ORDER_BOMBARD")) % m_planet % m_ship) + ExecutedTag(this); }

bool BombardOrder::Check(int empire_id, int ship_id, int planet_id,
                         const ScriptingContext& context)
{
    const Universe& universe = context.ContextUniverse();
    const ObjectMap& objects = context.ContextObjects();

    if (empire_id == ALL_EMPIRES) {
        ErrorLogger() << "BombardOrder::Check() : empire " << empire_id << " is not an empire";
        return false;
    }

    auto ship = objects.get<Ship>(ship_id);
    if (!ship) {
        ErrorLogger() << "BombardOrder::ExecuteImpl couldn't get ship with id " << ship_id;
        return false;
    }
    if (!ship->CanBombard(universe)) {
        ErrorLogger() << "BombardOrder::ExecuteImpl got ship that can't bombard";
        return false;
    }
    if (!ship->OwnedBy(empire_id)) {
        ErrorLogger() << "BombardOrder::ExecuteImpl got ship that isn't owned by the order-issuing empire";
        return false;
    }

    auto planet = objects.get<Planet>(planet_id);
    if (!planet) {
        ErrorLogger() << "BombardOrder::ExecuteImpl couldn't get planet with id " << planet_id;
        return false;
    }
    if (planet->OwnedBy(empire_id)) {
        ErrorLogger() << "BombardOrder::ExecuteImpl given planet that is already owned by the order-issuing empire";
        return false;
    }
    if (!planet->Unowned() && context.ContextDiploStatus(planet->Owner(), empire_id) != DiplomaticStatus::DIPLO_WAR) {
        ErrorLogger() << "BombardOrder::ExecuteImpl given planet owned by an empire not at war with order-issuing empire";
        return false;
    }
    if (universe.GetObjectVisibilityByEmpire(planet_id, empire_id) < Visibility::VIS_BASIC_VISIBILITY) {
        ErrorLogger() << "BombardOrder::ExecuteImpl given planet that empire reportedly has insufficient visibility of, but will be allowed to proceed pending investigation";
    }

    int ship_system_id = ship->SystemID();
    if (ship_system_id == INVALID_OBJECT_ID) {
        ErrorLogger() << "BombardOrder::ExecuteImpl given id of ship not in a system";
        return false;
    }
    int planet_system_id = planet->SystemID();
    if (ship_system_id != planet_system_id) {
        ErrorLogger() << "BombardOrder::ExecuteImpl given ids of ship and planet not in the same system";
        return false;
    }

    return true;
}

void BombardOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_ship, m_planet, context))
        return;

    ObjectMap& objects{context.ContextObjects()};
    auto ship = objects.get<Ship>(m_ship);
    auto planet = objects.get<Planet>(m_planet);

    // note: multiple ships, from same or different empires, can bombard the same planet on the same turn
    DebugLogger() << "BombardOrder::ExecuteImpl set for ship " << m_ship << " "
                  << ship->Name() << " to bombard planet " << m_planet << " "
                  << planet->Name();
    planet->SetIsAboutToBeBombarded(true);
    ship->SetBombardPlanet(m_planet);

    if (auto fleet = objects.get<Fleet>(ship->FleetID()))
        fleet->StateChangedSignal();
}

bool BombardOrder::UndoImpl(ScriptingContext& context) const {
    ObjectMap& objects{context.ContextObjects()};

    auto planet = objects.get<Planet>(m_planet);
    if (!planet) {
        ErrorLogger() << "BombardOrder::UndoImpl couldn't get planet with id " << m_planet;
        return false;
    }

    auto ship = objects.get<Ship>(m_ship);
    if (!ship) {
        ErrorLogger() << "BombardOrder::UndoImpl couldn't get ship with id " << m_ship;
        return false;
    }
    if (ship->OrderedBombardPlanet() != m_planet) {
        ErrorLogger() << "BombardOrder::UndoImpl ship is not about to bombard planet";
        return false;
    }

    planet->SetIsAboutToBeBombarded(false);
    ship->ClearBombardPlanet();

    if (auto fleet = objects.get<Fleet>(ship->FleetID()))
        fleet->StateChangedSignal();

    return true;
}

////////////////////////////////////////////////
// ChangeFocusOrder
////////////////////////////////////////////////
ChangeFocusOrder::ChangeFocusOrder(int empire, int planet, std::string focus, const ScriptingContext& context) :
    Order(empire),
    m_planet(planet),
    m_focus(std::move(focus))
{ Check(empire, m_planet, m_focus, context); }

std::string ChangeFocusOrder::Dump() const
{ return boost::io::str(FlexibleFormat(UserString("ORDER_FOCUS_CHANGE")) % m_planet % m_focus) + ExecutedTag(this); }

bool ChangeFocusOrder::Check(int empire_id, int planet_id, const std::string& focus,
                             const ScriptingContext& context)
{
    auto planet = context.ContextObjects().getRaw<Planet>(planet_id);

    if (!planet) {
        ErrorLogger() << "Invalid planet id " << planet_id << " specified in change planet focus order.";
        return false;
    }

    if (!planet->OwnedBy(empire_id)) {
        ErrorLogger() << "Empire " << empire_id
                      << " attempted to issue change planet focus to another's planet: " << planet_id;
        return false;
    }

    if (!planet->FocusAvailable(focus, context)) {
        ErrorLogger() << "IssueChangeFocusOrder : invalid focus (" << focus
                      << ") for specified for planet " << planet_id << " and empire " << empire_id;
        // TODO: further clarify why invalid? get species and check that it has the focus, and then
        //       if the location condition fails?
        return false;
    }

    return true;
}

void ChangeFocusOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_planet, m_focus, context))
        return;

    auto planet = context.ContextObjects().getRaw<Planet>(m_planet);

    planet->SetFocus(m_focus, context);
}

////////////////////////////////////////////////
// PolicyOrder
////////////////////////////////////////////////
PolicyOrder::PolicyOrder(int empire, std::string name, std::string category, bool adopt, int slot) :
    Order(empire),
    m_policy_name(std::move(name)),
    m_category(std::move(category)),
    m_slot(slot),
    m_adopt(adopt)
{}

std::string PolicyOrder::Dump() const {
    const auto& template_str = m_adopt ? UserString("ORDER_POLICY_ADOPT") : UserString("ORDER_POLICY_ABANDON");
    return boost::io::str(FlexibleFormat(template_str)
                          % m_policy_name % m_category % m_slot) + ExecutedTag(this);
}

void PolicyOrder::ExecuteImpl(ScriptingContext& context) const {
    auto empire = GetValidatedEmpire(context);
    if (m_adopt) {
        DebugLogger() << "PolicyOrder adopt " << m_policy_name << " in category " << m_category
                      << " in slot " << m_slot;
        empire->AdoptPolicy(m_policy_name, m_category, context, m_adopt, m_slot);
    } else if (!m_revert) {
        DebugLogger() << "PolicyOrder revoke " << m_policy_name << " from category " << m_category
                      << " in slot " << m_slot;
        empire->AdoptPolicy(m_policy_name, m_category, context, m_adopt, m_slot);
    } else {
        empire->RevertPolicies();
    }
}

////////////////////////////////////////////////
// ResearchQueueOrder
////////////////////////////////////////////////
ResearchQueueOrder::ResearchQueueOrder(int empire, std::string tech_name) :
    Order(empire),
    m_tech_name(std::move(tech_name)),
    m_remove(true)
{}

ResearchQueueOrder::ResearchQueueOrder(int empire, std::string tech_name, int position) :
    Order(empire),
    m_tech_name(std::move(tech_name)),
    m_position(position)
{}

ResearchQueueOrder::ResearchQueueOrder(int empire, std::string tech_name, bool pause, float dummy) :
    Order(empire),
    m_tech_name(std::move(tech_name)),
    m_pause(pause ? PAUSE : RESUME)
{}

std::string ResearchQueueOrder::Dump() const {
    const auto& template_str = [this]() -> const auto& {
        if (m_remove)
            return UserString("ORDER_RESEARCH_REMOVE");
        else if (m_pause == PAUSE)
            return UserString("ORDER_RESEARCH_PAUSE");
        else if (m_pause == RESUME)
            return UserString("ORDER_RESEARCH_RESUME");
        else
            return UserString("ORDER_RESEARCH_ENQUEUE_AT");
    }();

    const auto& tech_name = UserStringExists(m_tech_name) ? UserString(m_tech_name) : m_tech_name;
    return boost::io::str(FlexibleFormat(template_str) % tech_name % m_position) + ExecutedTag(this);
}

void ResearchQueueOrder::ExecuteImpl(ScriptingContext& context) const {
    auto empire = GetValidatedEmpire(context);

    if (m_remove) {
        DebugLogger() << "ResearchQueueOrder::ExecuteImpl: removing from queue tech: " << m_tech_name;
        empire->RemoveTechFromQueue(m_tech_name);
    } else if (m_pause == PAUSE) {
        DebugLogger() << "ResearchQueueOrder::ExecuteImpl: pausing tech: " << m_tech_name;
        empire->PauseResearch(m_tech_name);
    } else if (m_pause == RESUME) {
        DebugLogger() << "ResearchQueueOrder::ExecuteImpl: unpausing tech: " << m_tech_name;
        empire->ResumeResearch(m_tech_name);
    } else if (m_position != INVALID_INDEX) {
        DebugLogger() << "ResearchQueueOrder::ExecuteImpl: adding tech to queue: " << m_tech_name;
        empire->PlaceTechInQueue(m_tech_name, m_position);
    } else {
        ErrorLogger() << "ResearchQueueOrder::ExecuteImpl: Malformed";
    }
}

////////////////////////////////////////////////
// ProductionQueueOrder
////////////////////////////////////////////////
ProductionQueueOrder::ProductionQueueOrder(ProdQueueOrderAction action, int empire,
                                           ProductionQueue::ProductionItem item,
                                           int number, int location, int pos) :
    Order(empire),
    m_item(std::move(item)),
    m_location(location),
    m_new_quantity(number),
    m_new_index(pos),
    m_uuid(boost::uuids::random_generator()()),
    m_action(action)
{
    if (action != ProdQueueOrderAction::PLACE_IN_QUEUE)
        ErrorLogger() << "ProductionQueueOrder called with parameters for placing in queue but with another action";
}

ProductionQueueOrder::ProductionQueueOrder(ProdQueueOrderAction action, int empire,
                                           boost::uuids::uuid uuid, int num1, int num2) :
    Order(empire),
    m_uuid(uuid),
    m_action(action)
{
    switch(m_action) {
    case ProdQueueOrderAction::REMOVE_FROM_QUEUE:
    case ProdQueueOrderAction::UNREMOVE_FROM_QUEUE:
        break;
    case ProdQueueOrderAction::SPLIT_INCOMPLETE:
    case ProdQueueOrderAction::DUPLICATE_ITEM:
        m_uuid2 = boost::uuids::random_generator()();
        break;
    case ProdQueueOrderAction::SET_QUANTITY_AND_BLOCK_SIZE:
        m_new_quantity = num1;
        m_new_blocksize = num2;
        break;
    case ProdQueueOrderAction::SET_QUANTITY:
        m_new_quantity = num1;
        break;
    case ProdQueueOrderAction::MOVE_ITEM_TO_INDEX:
        m_new_index = num1;
        break;
    case ProdQueueOrderAction::SET_RALLY_POINT:
        m_rally_point_id = num1;
        break;
    case ProdQueueOrderAction::PAUSE_PRODUCTION:
    case ProdQueueOrderAction::RESUME_PRODUCTION:
    case ProdQueueOrderAction::ALLOW_STOCKPILE_USE:
    case ProdQueueOrderAction::DISALLOW_STOCKPILE_USE:
        break;
    default:
        ErrorLogger() << "ProductionQueueOrder given unrecognized action!";
    }
}

std::string ProductionQueueOrder::Dump() const
{ return UserString("ORDER_PRODUCTION"); }

void ProductionQueueOrder::ExecuteImpl(ScriptingContext& context) const {
    try {
        auto empire = GetValidatedEmpire(context);

        switch(m_action) {
        case ProdQueueOrderAction::PLACE_IN_QUEUE: {
            if (m_item.build_type == BuildType::BT_BUILDING ||
                m_item.build_type == BuildType::BT_SHIP ||
                m_item.build_type == BuildType::BT_STOCKPILE)
            {
                DebugLogger() << "ProductionQueueOrder place in queue: " << m_item.Dump()
                              << "  at index: " << m_new_index;
                empire->PlaceProductionOnQueue(m_item, m_uuid, m_new_quantity, 1, m_location, m_new_index);
            } else {
                ErrorLogger() << "ProductionQueueOrder tried to place invalid build type in queue!";
            }
            break;
        }
        case ProdQueueOrderAction::REMOVE_FROM_QUEUE: {
            const auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to remove invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder removing item at index: " << idx;
                empire->MarkToBeRemoved(idx);
            }
            break;
        }
        case ProdQueueOrderAction::UNREMOVE_FROM_QUEUE: {
            const auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to unremove invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder unremoving item at index: " << idx;
                empire->MarkNotToBeRemoved(idx);
            }
            break;
        }
        case ProdQueueOrderAction::SPLIT_INCOMPLETE: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to split invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder splitting incomplete from item";
                empire->SplitIncompleteProductionItem(idx, m_uuid2);
            }
            break;
        }
        case ProdQueueOrderAction::DUPLICATE_ITEM: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to duplicate invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder duplicating item";
                empire->DuplicateProductionItem(idx, m_uuid2);
            }
            break;
        }
        case ProdQueueOrderAction::SET_QUANTITY_AND_BLOCK_SIZE: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to set quantity and blocksize of invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder setting quantity and block size";
                empire->SetProductionQuantityAndBlocksize(idx, m_new_quantity, m_new_blocksize);
            }
            break;
        }
        case ProdQueueOrderAction::SET_QUANTITY: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to set quantity of invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder setting quantity " << m_new_quantity;
                empire->SetProductionQuantity(idx, m_new_quantity);
            }
            break;
        }
        case ProdQueueOrderAction::MOVE_ITEM_TO_INDEX: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to move invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder moving to index " << m_new_index;
                empire->MoveProductionWithinQueue(idx, m_new_index);
            }
            break;
        }
        case ProdQueueOrderAction::SET_RALLY_POINT: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to set rally point of invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder setting rally point to " << m_rally_point_id;
                empire->SetProductionRallyPoint(idx, m_rally_point_id);
            }
            break;
        }
        case ProdQueueOrderAction::PAUSE_PRODUCTION: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to pause invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder pausing";
                empire->PauseProduction(idx);
            }
            break;
        }
        case ProdQueueOrderAction::RESUME_PRODUCTION: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to resume invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder resuming";
                empire->ResumeProduction(idx);
            }
            break;
        }
        case ProdQueueOrderAction::ALLOW_STOCKPILE_USE: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to allow stockpiling on invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder allowing stockpile";
                empire->AllowUseImperialPP(idx, true);
            }
            break;
        }
        case ProdQueueOrderAction::DISALLOW_STOCKPILE_USE: {
            auto idx = empire->GetProductionQueue().IndexOfUUID(m_uuid);
            if (idx == -1) {
                ErrorLogger() << "ProductionQueueOrder asked to disallow stockpiling on invalid UUID: " << boost::uuids::to_string(m_uuid);
            } else {
                DebugLogger() << "ProductionQueueOrder disallowing stockpile";
                empire->AllowUseImperialPP(idx, false);
            }
            break;
        }
        default:
            ErrorLogger() << "ProductionQueueOrder::ExecuteImpl got invalid action";
        }
    } catch (const std::exception& e) {
        ErrorLogger() << "Production order execution threw exception: " << e.what();
        throw;
    }
}

////////////////////////////////////////////////
// ShipDesignOrder
////////////////////////////////////////////////
ShipDesignOrder::ShipDesignOrder(int empire, int existing_design_id_to_remember,
                                 const ScriptingContext& context) :
    Order(empire),
    m_design_id(existing_design_id_to_remember)
{ CheckRemember(empire, m_design_id, context); }

ShipDesignOrder::ShipDesignOrder(int empire, int design_id_to_erase, bool dummy,
                                 const ScriptingContext& context) :
    Order(empire),
    m_design_id(design_id_to_erase),
    m_delete_design_from_empire(true)
{ CheckErase(empire, m_design_id, m_delete_design_from_empire, context); }

ShipDesignOrder::ShipDesignOrder(int empire, const ShipDesign& ship_design,
                                 const ScriptingContext& context) :
    Order(empire),
    m_uuid(ship_design.UUID()),
    m_name(ship_design.Name(false)),
    m_description(ship_design.Description(false)),
    m_hull(ship_design.Hull()),
    m_parts(ship_design.Parts()),
    m_icon(ship_design.Icon()),
    m_3D_model(ship_design.Model()),
    m_design_id(INVALID_DESIGN_ID),
    m_designed_on_turn(ship_design.DesignedOnTurn()),
    m_create_new_design(true),
    m_is_monster(ship_design.IsMonster()),
    m_name_desc_in_stringtable(ship_design.LookupInStringtable())
{ CheckNew(empire, m_name, m_description, m_hull, m_parts, context); }

ShipDesignOrder::ShipDesignOrder(int empire, int existing_design_id,
                                 std::string new_name, std::string new_description,
                                 const ScriptingContext& context) :
    Order(empire),
    m_name(std::move(new_name)),
    m_description(std::move(new_description)),
    m_design_id(existing_design_id),
    m_update_name_or_description(true)
{ CheckRename(empire, m_design_id, m_name, m_description, context); }

std::string ShipDesignOrder::Dump() const
{ return UserString("ORDER_SHIP_DESIGN"); }

void ShipDesignOrder::ExecuteImpl(ScriptingContext& context) const {
    auto empire = GetValidatedEmpire(context);

    Universe& universe = context.ContextUniverse();

    if (m_delete_design_from_empire) {
        if (!CheckErase(EmpireID(), m_design_id, m_delete_design_from_empire, context))
            return;

        empire->RemoveShipDesign(m_design_id);

    } else if (m_create_new_design) {
        if (!CheckNew(EmpireID(), m_name, m_description, m_hull, m_parts, context))
            return;

        try {
            ShipDesign new_ship_design(std::invalid_argument(""), m_name, m_description,
                                       m_designed_on_turn, EmpireID(), m_hull, m_parts,
                                       m_icon, m_3D_model, m_name_desc_in_stringtable,
                                       m_is_monster, m_uuid);

            if (m_design_id == INVALID_DESIGN_ID) {
                // On the client create a new design id
                m_design_id = universe.InsertShipDesign(std::move(new_ship_design));
                DebugLogger() << "ShipDesignOrder::ExecuteImpl inserted new ship design ID " << m_design_id;

            } else {
                // On the server use the design id passed from the client
                const auto success = universe.InsertShipDesignID(std::move(new_ship_design), EmpireID(),
                                                                 m_design_id);
                if (!success) {
                    ErrorLogger() << "Couldn't insert ship design by ID " << m_design_id;
                    return;
                }
            }

            universe.SetEmpireKnowledgeOfShipDesign(m_design_id, EmpireID());
            empire->AddShipDesign(m_design_id, universe);


        } catch (const std::exception& e) {
            ErrorLogger() << "Couldn't create ship design: " << e.what();
            return;
        }

    } else if (m_update_name_or_description) {
        if (!CheckRename(EmpireID(), m_design_id, m_name, m_description, context))
            return;

        universe.RenameShipDesign(m_design_id, m_name, m_description);

    } else {
        // player is ordering empire to retain a particular design, so that is can
        // be used to construct ships by that empire.
        if (!CheckRemember(EmpireID(), m_design_id, context))
            return;
        empire->AddShipDesign(m_design_id, universe);

        // TODO: consider removing this order, so that an empire needs to use
        // espionage or influence to gain access to a ship design made by another
        // player
    }
}

bool ShipDesignOrder::CheckRemember(int empire_id, int existing_design_id_to_remember,
                                    const ScriptingContext& context)
{
    const auto empire = context.GetEmpire(empire_id);
    if (!empire) {
        ErrorLogger() << "ShipDesignOrder : given invalid empire id";
        return false;
    }

    // check if empire is already remembering the design
    if (empire->ShipDesignKept(existing_design_id_to_remember)) {
        ErrorLogger() << "Empire " << empire_id
                      << " tried to remember a ShipDesign id = " << existing_design_id_to_remember
                      << " that was already being remembered";
        return false;
    }

    // check if the empire can see any objects that have this design (thus enabling it to be copied)
    auto& empire_known_design_ids = context.ContextUniverse().EmpireKnownShipDesignIDs(empire_id);
    if (!empire_known_design_ids.contains(existing_design_id_to_remember)) {
        ErrorLogger() << "Empire " << empire_id
                      << " tried to remember a ShipDesign id = " << existing_design_id_to_remember
                      << " that this empire hasn't seen";
        return false;
    }

    return true;
}

bool ShipDesignOrder::CheckErase(int empire_id, int design_id_to_erase, bool dummy,
                                 const ScriptingContext& context)
{
    const auto empire = context.GetEmpire(empire_id);
    if (!empire) {
        ErrorLogger() << "ShipDesignOrder : given invalid empire id";
        return false;
    }

    // player is ordering empire to forget about a particular design
    if (!empire->ShipDesignKept(design_id_to_erase)) {
        ErrorLogger() << "Empire " << empire_id << " tried to remove a ShipDesign id = " << design_id_to_erase
                      << " that the empire wasn't remembering";
        return false;
    }

    return true;
}

bool ShipDesignOrder::CheckNew(int empire_id, const std::string& name, const std::string& desc,
                               const std::string& hull, const std::vector<std::string>& parts,
                               const ScriptingContext& context)
{
    const auto empire = context.GetEmpire(empire_id);
    if (!empire) {
        ErrorLogger() << "ShipDesignOrder : given invalid empire id";
        return false;
    }

    // TODO: check hull and parts

    return true;
}

bool ShipDesignOrder::CheckRename(int empire_id, int existing_design_id, const std::string& new_name,
                                  const std::string& new_description, const ScriptingContext& context)
{
    const auto empire = context.GetEmpire(empire_id);
    if (!empire) {
        ErrorLogger() << "ShipDesignOrder : given invalid empire id";
        return false;
    }

    const auto& universe = context.ContextUniverse();
    // check if a design with this ID exists
    auto existing = universe.GetShipDesign(existing_design_id);
    if (!existing) {
        ErrorLogger() << "Empire " << empire_id
                      << " tried to rename a ShipDesign with an id, " << existing_design_id
                      << " that does not exist";
        return false;
    }

    // player is ordering empire to rename a design
    const auto& empire_known_design_ids = universe.EmpireKnownShipDesignIDs(empire_id);
    auto design_it = empire_known_design_ids.find(existing_design_id);
    if (design_it == empire_known_design_ids.end()) {
        ErrorLogger() << "Empire " << empire_id
                      << " tried to rename/redescribe a ShipDesign id = " << existing_design_id
                      << " that this empire hasn't seen";
        return false;
    }
    const ShipDesign* design = universe.GetShipDesign(*design_it);
    if (!design) {
        ErrorLogger() << "Empire " << empire_id
                      << " tried to rename/redescribe a ShipDesign id = " << existing_design_id
                      << " that doesn't exist (but this empire has seen it)!";
        return false;
    }
    if (design->DesignedByEmpire() != empire_id) {
        ErrorLogger() << "Empire " << empire_id
                      << " tried to rename/redescribe a ShipDesign id = " << existing_design_id
                      << " that isn't owned by this empire!";
        return false;
    }

    return true;
}

////////////////////////////////////////////////
// ScrapOrder
////////////////////////////////////////////////
ScrapOrder::ScrapOrder(int empire, int object_id, const ScriptingContext& context) :
    Order(empire),
    m_object_id(object_id)
{
    if (!Check(empire, object_id, context))
        return;
}

std::string ScrapOrder::Dump() const
{ return UserString("ORDER_SCRAP"); }

bool ScrapOrder::Check(int empire_id, int object_id, const ScriptingContext& context) {
    auto obj = context.ContextObjects().get(object_id);

    if (!obj) {
        ErrorLogger() << "IssueScrapOrder : passed an invalid object_id";
        return false;
    }

    if (!obj->OwnedBy(empire_id)) {
        ErrorLogger() << "IssueScrapOrder : passed object_id of object not owned by player";
        return false;
    }

    if (obj->ObjectType() != UniverseObjectType::OBJ_SHIP && obj->ObjectType() != UniverseObjectType::OBJ_BUILDING) {
        ErrorLogger() << "ScrapOrder::Check : passed object that is not a ship or building";
        return false;
    }

    auto ship = context.ContextObjects().get<Ship>(object_id);
    if (ship && ship->SystemID() == INVALID_OBJECT_ID)
        ErrorLogger() << "ScrapOrder::Check : can scrap a traveling ship";

    return true;
}

void ScrapOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_object_id, context))
        return;

    ObjectMap& objects{context.ContextObjects()};

    if (auto ship = objects.get<Ship>(m_object_id)) {
        ship->SetOrderedScrapped(true);
    } else if (auto building = objects.get<Building>(m_object_id)) {
        building->SetOrderedScrapped(true);
    }
}

bool ScrapOrder::UndoImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);
    int empire_id = EmpireID();

    ObjectMap& objects{context.ContextObjects()};

    if (auto ship = objects.get<Ship>(m_object_id)) {
        if (ship->OwnedBy(empire_id))
            ship->SetOrderedScrapped(false);
    } else if (auto building = objects.get<Building>(m_object_id)) {
        if (building->OwnedBy(empire_id))
            building->SetOrderedScrapped(false);
    } else {
        return false;
    }
    return true;
}

////////////////////////////////////////////////
// AggressiveOrder
////////////////////////////////////////////////
AggressiveOrder::AggressiveOrder(int empire, int object_id, FleetAggression aggression,
                                 const ScriptingContext& context) :
    Order(empire),
    m_object_id(object_id),
    m_aggression(aggression)
{
    if (!Check(empire, object_id, m_aggression, context))
        return;
}

std::string AggressiveOrder::Dump() const
{ return UserString("ORDER_FLEET_AGGRESSION"); }

bool AggressiveOrder::Check(int empire_id, int object_id, FleetAggression aggression,
                            const ScriptingContext& context)
{
    const ObjectMap& objects{context.ContextObjects()};

    auto fleet = objects.get<Fleet>(object_id);
    if (!fleet) {
        ErrorLogger() << "IssueAggressionOrder : no fleet with passed id";
        return false;
    }

    if (!fleet->OwnedBy(empire_id)) {
        ErrorLogger() << "IssueAggressionOrder : passed object_id of object not owned by player";
        return false;
    }

    return true;
}

void AggressiveOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_object_id, m_aggression, context))
        return;

    if (auto fleet = context.ContextObjects().get<Fleet>(m_object_id))
        fleet->SetAggression(m_aggression);
    else
        ErrorLogger() << "AggressiveOrder::ExecuteImpl couldn't find fleet with id " << m_object_id;
}

/////////////////////////////////////////////////////
// GiveObjectToEmpireOrder
/////////////////////////////////////////////////////
GiveObjectToEmpireOrder::GiveObjectToEmpireOrder(int empire, int object_id, int recipient,
                                                 const ScriptingContext& context) :
    Order(empire),
    m_object_id(object_id),
    m_recipient_empire_id(recipient)
{
    if (!Check(empire, object_id, recipient, context))
        return;
}

std::string GiveObjectToEmpireOrder::Dump() const
{ return UserString("ORDER_GIVE_TO_EMPIRE"); }

bool GiveObjectToEmpireOrder::Check(int empire_id, int object_id, int recipient_empire_id,
                                    const ScriptingContext& context)
{
    if (!context.GetEmpire(recipient_empire_id)) {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : given invalid recipient empire id";
        return false;
    }
    const auto giver_empire = context.GetEmpire(empire_id);
    if (!giver_empire) {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : given invalid giver empire id";
        return false;
    }
    if (giver_empire->CapitalID() == object_id) {
        ErrorLogger() << "IssueGiverObjectToEmpireOrder : giving away capital not allowed";
        return false;
    }


    const auto dip = context.ContextDiploStatus(empire_id, recipient_empire_id);
    if (dip < DiplomaticStatus::DIPLO_PEACE) {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : attempting to give to empire not at peace";
        return false;
    }

    const ObjectMap& objects{context.ContextObjects()};

    const auto obj = objects.get(object_id);
    if (!obj) {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : passed invalid object id";
        return false;
    }

    if (!obj->OwnedBy(empire_id)) {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : passed object not owned by player";
        return false;
    }

    const auto system = objects.get<System>(obj->SystemID());
    if (!system) {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : couldn't get system of object";
        return false;
    }

    if (obj->ObjectType() != UniverseObjectType::OBJ_FLEET &&
        obj->ObjectType() != UniverseObjectType::OBJ_PLANET)
    {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : passed object that is not a fleet or planet";
        return false;
    }

    const auto system_objects = objects.findRaw<const UniverseObject>(system->ObjectIDs());
    if (!std::any_of(system_objects.begin(), system_objects.end(),
                     [recipient_empire_id](const auto& o){ return o->Owner() == recipient_empire_id; }))
    {
        ErrorLogger() << "IssueGiveObjectToEmpireOrder : recipient empire has nothing in system";
        return false;
    }

    return true;
}

void GiveObjectToEmpireOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);

    if (!Check(EmpireID(), m_object_id, m_recipient_empire_id, context))
        return;

    if (auto fleet = context.ContextObjects().get<Fleet>(m_object_id))
        fleet->SetGiveToEmpire(m_recipient_empire_id);
    else if (auto planet = context.ContextObjects().get<Planet>(m_object_id))
        planet->SetGiveToEmpire(m_recipient_empire_id);
}

bool GiveObjectToEmpireOrder::UndoImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);
    int empire_id = EmpireID();

    ObjectMap& objects{context.ContextObjects()};

    if (auto fleet = objects.get<Fleet>(m_object_id)) {
        if (fleet->OwnedBy(empire_id)) {
            fleet->ClearGiveToEmpire();
            return true;
        }
    } else if (auto planet = objects.get<Planet>(m_object_id)) {
        if (planet->OwnedBy(empire_id)) {
            planet->ClearGiveToEmpire();
            return true;
        }
    }
    return false;
}

////////////////////////////////////////////////
// ForgetOrder
////////////////////////////////////////////////
ForgetOrder::ForgetOrder(int empire, int object_id) :
    Order(empire),
    m_object_id(object_id)
{}

std::string ForgetOrder::Dump() const
{ return UserString("ORDER_FORGET"); }

void ForgetOrder::ExecuteImpl(ScriptingContext& context) const {
    GetValidatedEmpire(context);
    int empire_id = EmpireID();

    DebugLogger() << "ForgetOrder::ExecuteImpl empire: " << empire_id
                  << " for object: " << m_object_id;

    context.ContextUniverse().ForgetKnownObject(empire_id, m_object_id);
}